python 列表、元组、集合、字典、循环遍历数据结构
- python 列表、元組、集合、字典、數據結構的循環(整理自python文檔)
- 列表-list-用方括號標注,逗號分隔的一組值
- list 的 方法
- 對list添加、插入、刪除、查找、排列、翻轉
- list.append(x)
- list.extend(iterable)
- list.insert(i, x)
- list.remove(x)
- list.pop([i])
- list.clear()
- list.index(x[, start[, end]])
- list.count(x)
- list.sort(*, key=None, reverse=False)
- list.reverse()
- list.copy()
- list 實現堆棧-append和pop
- list 實現隊列
- 創建list
- 列表推導式創建list
- 嵌套的列表推導式
- del語句
- del-從列表中移除元素、移除切片、清空列表
- del-刪除變量
- 元組和序列-多個用逗號隔開的值
- 元組的格式-圓括號
- 元組和列表-不可變 與 可變
- 創建元組
- 元組序列解包
- 集合-由不重復元素組成的無序容器。
- 創建集合-用花括號或 `set() ` 函數
- 字典
- 字典的索引(鍵)-不可變類型
- 字典的鍵-唯一
- 創建字典
- 字典的主要用途-通過關鍵字存儲、提取值
- 數據結構的循環
- 字典中循環-取出鍵和值-items()
- 序列中循環-取出位置和值-enumerate()
- 循環多個序列-元素匹配-zip()
- 逆向循環-reversed()
- 指定順序循環序列-sorted()
- 循環遍歷序列中的唯一元素-set()
- 循環中修改列表的內容-創建新列表
python 列表、元組、集合、字典、數據結構的循環(整理自python文檔)
列表-list-用方括號標注,逗號分隔的一組值
列表 ,是用方括號標注,逗號分隔的一組值。可以包含不同類型的元素,也支持索引和切片。
列表數據類型支持很多方法,列表對象的所有方法所示如下:
list 的 方法
對list添加、插入、刪除、查找、排列、翻轉
list.append(x)
在列表末尾添加一個元素,相當于 a[len(a):] = [x] 。
list.extend(iterable)
用可迭代對象的元素擴展列表。相當于 a[len(a):] = iterable 。
list.insert(i, x)
在指定位置插入元素。第一個參數是插入元素的索引,因此,a.insert(0, x) 在列表開頭插入元素, a.insert(len(a), x) 等同于 a.append(x) 。
list.remove(x)
從列表中刪除第一個值為 x 的元素。未找到指定元素時,觸發 ValueError 異常。
list.pop([i])
刪除列表中指定位置的元素,并返回被刪除的元素。未指定位置時,a.pop() 刪除并返回列表的最后一個元素。(方法簽名中 i 兩邊的方括號表示該參數是可選的,不是要求輸入方括號。這種表示法常見于 Python 參考庫)。
list.clear()
刪除列表里的所有元素,相當于 del a[:] 。
list.index(x[, start[, end]])
返回列表中第一個值為 x 的元素的零基索引。未找到指定元素時,觸發 ValueError 異常。
可選參數 start 和 end 是切片符號,用于將搜索限制為列表的特定子序列。返回的索引是相對于整個序列的開始計算的,而不是 start 參數。
list.count(x)
返回列表中元素 x 出現的次數。
list.sort(*, key=None, reverse=False)
就地排序列表中的元素(要了解自定義排序參數,詳見 sorted())。
list.reverse()
翻轉列表中的元素。
list.copy()
返回列表的淺拷貝。相當于 a[:] 。
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] >>> fruits.count('apple') 2 >>> fruits.count('tangerine') 0 >>> fruits.index('banana') 3 >>> fruits.index('banana', 4) # Find next banana starting a position 4 6 >>> fruits.reverse() >>> fruits ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange'] >>> fruits.append('grape') >>> fruits ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape'] >>> fruits.sort() >>> fruits ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear'] >>> fruits.pop() 'pear'insert、remove、sort 等方法只修改列表,不輸出返回值——返回的默認值為 None 。
不是所有數據都可以排序或比較。例如,[None, ‘hello’, 10] 就不可排序,因為整數不能與字符串對比,而 None 不能與其他類型對比。
list 實現堆棧-append和pop
使用列表方法實現堆棧,最后插入的最先取出(“后進先出”)。
把元素添加到堆棧的頂端,使用 append() 。
從堆棧頂部取出元素,使用 pop()
>>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4]list 實現隊列
列表也可以用作隊列,最先加入的元素,最先取出(“先進先出”)。
列表作為隊列的效率很低。因為,在列表末尾添加和刪除元素非常快,但在列表開頭插入或移除元素卻很慢(因為所有其他元素都必須移動一位)
實現隊列最好用 [collections.deque],可以快速從兩端添加或刪除元素
>>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham'])創建list
對序列或可迭代對象中的每個元素應用某種操作,用生成的結果創建新的列表。
例如,創建平方值的列表:
>>> squares = [] >>> for x in range(10): ... squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]列表推導式創建list
squares = [x**2 for x in range(10)]列表推導式的方括號內包含以下內容:
一個表達式,后面為一個 for 子句,然后,是零個或多個 for 或 if 子句。
結果是由表達式依據 for 和 if 子句求值計算而得出一個新列表。
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]等價于:
>>> combs = [] >>> for x in [1,2,3]: ... for y in [3,1,4]: ... if x != y: ... combs.append((x, y)) ... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]其他例子:
>>> vec = [-4, -2, 0, 2, 4] >>> # create a new list with the values doubled >>> [x*2 for x in vec] [-8, -4, 0, 4, 8]>>> # filter the list to exclude negative numbers >>> [x for x in vec if x >= 0] [0, 2, 4]>>> # apply a function to all the elements >>> [abs(x) for x in vec] [4, 2, 0, 2, 4]>>> # call a method on each element >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>> [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit']>>> # create a list of 2-tuples like (number, square) >>> [(x, x**2) for x in range(6)] [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]>>> # the tuple must be parenthesized, otherwise an error is raised >>> [x, x**2 for x in range(6)]File "<stdin>", line 1, in <module>[x, x**2 for x in range(6)]^ SyntaxError: invalid syntax>>> # flatten a list using a listcomp with two 'for' >>> vec = [[1,2,3], [4,5,6], [7,8,9]] >>> [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9]>>> from math import pi >>> [str(round(pi, i)) for i in range(1, 6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159']嵌套的列表推導式
>>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ]下面的列表推導式可以轉置行列:
>>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]等價于:
>>> transposed = [] >>> for i in range(4): ... # the following 3 lines implement the nested listcomp ,row是行的意思 ... transposed_row = [] ... for row in matrix:#matrix 有三行 ... transposed_row.append(row[i]) ... transposed.append(transposed_row) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]等價于:
>>> list(zip(*matrix)) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]del語句
del-從列表中移除元素、移除切片、清空列表
[del]語句按索引,而不是值從列表中移除元素。與返回值的 pop() 方法不同, del 語句也可以從列表中移除切片,或清空整個列表(之前是將空列表賦值給切片)。
>>> a = [-1, 1, 66.25, 333, 333, 1234.5] >>> del a[0] >>> a [1, 66.25, 333, 333, 1234.5] >>> del a[2:4] >>> a [1, 66.25, 1234.5] >>> del a[:] >>> a []del-刪除變量
[del]也可以用來刪除整個變量:
>>> del a元組和序列-多個用逗號隔開的值
元組由多個用逗號隔開的值組成。
>>> t = 12345, 54321, 'hello!' >>> t[0] 12345 >>> t (12345, 54321, 'hello!') >>> # Tuples may be nested: ... u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) >>> # Tuples are immutable: ... t[0] = 88888 Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> # but they can contain mutable objects: ... v = ([1, 2, 3], [3, 2, 1]) >>> v ([1, 2, 3], [3, 2, 1])元組的格式-圓括號
輸出時,元組都要由圓括號標注。
輸入時,圓括號可有可無,不過經常是必須的(如果元組是更大的表達式的一部分)。
不允許為元組中的單個元素賦值,當然,可以創建含列表等可變對象的元組。
元組和列表-不可變 與 可變
元組與列表很像,但使用場景不同,用途也不同。
元組是 [immutable](不可變的),一般可包含異質元素序列,通過解包或索引訪問。
列表是 [mutable] (可變的),列表元素一般為同質類型,可迭代訪問。
創建元組
用一對空圓括號就可以創建空元組;只有一個元素的元組可以通過在這個元素后添加逗號來構建。
>>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',)元組序列解包
t = 12345, 54321, 'hello!' 是 元組打包 的例子:值 12345, 54321 和 'hello!' 一起被打包進元組。
序列解包 ,適用于右側的任何序列。序列解包時,左側變量與右側序列元素的數量應相等。
>>> x, y, z = t集合-由不重復元素組成的無序容器。
集合是由不重復元素組成的無序容器。
基本用法包括成員檢測、消除重復元素。
集合對象支持合集、交集、差集、對稱差分等數學運算。
創建集合-用花括號或 set() 函數
創建集合用花括號或 set() 函數。注意,創建空集合只能用 set(),不能用 {},{} 創建的是空字典。
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} >>> print(basket) # show that duplicates have been removed {'orange', 'banana', 'pear', 'apple'} >>> 'orange' in basket # fast membership testing True >>> 'crabgrass' in basket False>>> # Demonstrate set operations on unique letters from two words ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b # letters in a but not in b {'r', 'd', 'b'} >>> a | b # letters in a or b or both {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # letters in both a and b {'a', 'c'} >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'}與 [列表推導式]類似,集合也支持推導式:
>>> a = {x for x in 'abracadabra' if x not in 'abc'} >>> a {'r', 'd'}字典
字典的索引(鍵)-不可變類型
與以連續整數為索引的序列不同,字典以 關鍵字 為索引,關鍵字通常是字符串或數字,也可以是其他任意不可變類型。
只包含字符串、數字、元組的元組,也可以用作關鍵字。
但如果元組直接或間接地包含了可變對象,就不能用作關鍵字。
列表不能當關鍵字,因為列表可以用索引、切片、append() 、extend() 等方法修改。
字典的鍵-唯一
可以把字典理解為 鍵值對 的集合,但字典的鍵必須是唯一的。
創建字典
花括號 {} 用于創建空字典。
另一種初始化字典的方式是,在花括號里輸入逗號分隔的鍵值對,這也是字典的輸出方式。
dict() 構造函數可以直接用鍵值對序列創建字典:
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'guido': 4127, 'jack': 4098}推導式可以用任意鍵值表達式創建字典:
>>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36}關鍵字是比較簡單的字符串時,直接用關鍵字參數指定鍵值對更便捷:
>>> dict(sape=4139, guido=4127, jack=4098) {'sape': 4139, 'guido': 4127, 'jack': 4098}字典的主要用途-通過關鍵字存儲、提取值
字典的主要用途是通過關鍵字存儲、提取值。
用 del 可以刪除鍵值對。用已存在的關鍵字存儲值,與該關鍵字關聯的舊值會被取代。通過不存在的鍵提取值,則會報錯。
對字典執行 list(d) 操作,返回該字典中所有鍵的列表,按插入次序排列(如需排序,請使用 sorted(d))。
檢查字典里是否存在某個鍵,使用關鍵字 [in]。
以下是一些字典的簡單示例:
>>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'jack': 4098, 'sape': 4139, 'guido': 4127} >>> tel['jack'] 4098 >>> del tel['sape'] >>> tel['irv'] = 4127 >>> tel {'jack': 4098, 'guido': 4127, 'irv': 4127} >>> list(tel) ['jack', 'guido', 'irv'] >>> sorted(tel) ['guido', 'irv', 'jack'] >>> 'guido' in tel True >>> 'jack' not in tel False數據結構的循環
字典中循環-取出鍵和值-items()
在字典中循環時,用 items() 方法可同時取出鍵和對應的值:
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave序列中循環-取出位置和值-enumerate()
在序列中循環時,用 [enumerate()]函數可以同時取出位置索引和對應的值:
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe循環多個序列-元素匹配-zip()
同時循環兩個或多個序列時,用 [zip()] 函數可以將其內的元素一一匹配
>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print('What is your {0}? It is {1}.'.format(q, a)) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.逆向循環-reversed()
逆向循環序列時,先正向定位序列,然后調用 reversed() 函數:
>>> for i in reversed(range(1, 10, 2)): ... print(i) ... 9 7 5 3 1指定順序循環序列-sorted()
按指定順序循環序列,可以用 sorted()函數,在不改動原序列的基礎上,返回一個重新的序列
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for i in sorted(basket): ... print(i) ... apple apple banana orange orange pear循環遍歷序列中的唯一元素-set()
使用 set() 去除序列中的重復元素。使用 sorted() 加 set()則按排序后的順序,循環遍歷序列中的唯一元素:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print(f) ... apple banana orange pear循環中修改列表的內容-創建新列表
一般來說,在循環中修改列表的內容時,創建新列表比較簡單,且安全:
>>> import math >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8] >>> filtered_data = [] >>> for value in raw_data: ... if not math.isnan(value): ... filtered_data.append(value) ... >>> filtered_data [56.2, 51.7, 55.3, 52.5, 47.8]總結
以上是生活随笔為你收集整理的python 列表、元组、集合、字典、循环遍历数据结构的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通过共现矩阵和余弦相似度实现机器对单词的
- 下一篇: 准考证打印系统关闭怎么办_2019年执业