python菜鳥教程學習10:數據結構
- 2020 年 12 月 8 日
- 筆記
- CODING, Computer Science Knowledge Learning, Life sharing, Programming Language, Python, 基礎知識, 學習, 小白
列表方法
- list.append(x):把一個元素添加到列表的結尾,相當於 a[len(a):] = [x]。
- list.extend(L):通過添加指定列表的所有元素來擴充列表,相當於 a[len(a):] = L。
- list.insert(i, x):在指定位置插入一個元素。第一個參數是準備插入到其前面的那個元素的索引,例如 a.insert(0, x) 會插入到整個列表之前,而 a.insert(len(a), x) 相當於 a.append(x) 。
- list.remove(x):刪除列表中值為 x 的第一個元素。如果沒有這樣的元素,就會返回一個錯誤。
- list.pop([i]):從列表的指定位置移除元素,並將其返回。如果沒有指定索引,a.pop()返回最後一個元素。元素隨即從列表中被移除。(方法中 i 兩邊的方括弧表示這個參數是可選的,而不是要求你輸入一對方括弧,你會經常在 Python 庫參考手冊中遇到這樣的標記。)
- list.clear():移除列表中的所有項,等於del a[:]。
- list.index(x):返回列表中第一個值為 x 的元素的索引。如果沒有匹配的元素就會返回一個錯誤。
- list.count(x):返回 x 在列表中出現的次數。
- list.sort():對列表中的元素進行排序。
- list.reverse():倒排列表中的元素。
- list.copy():返回列表的淺複製,等於a[:]。
列表當堆棧使用
用 append() 方法可以把一個元素添加到堆棧頂。用不指定索引的 pop() 方法可以把一個元素從堆棧頂釋放出來。
列表當隊列使用
在隊列里第一加入的元素,第一個取出來;但是拿列表用作這樣的目的效率不高。在列表的最後添加或者彈出元素速度快,然而在列表裡插入或者從頭部彈出速度卻不快(因為所有其他的元素都得一個一個地移動)。
1 >>> from collections import deque 2 >>> queue = deque(["Eric", "John", "Michael"]) 3 >>> queue.append("Terry") # Terry arrives 4 >>> queue.append("Graham") # Graham arrives 5 >>> queue.popleft() # The first to arrive now leaves 6 'Eric' 7 >>> queue.popleft() # The second to arrive now leaves 8 'John' 9 >>> queue # Remaining queue in order of arrival 10 deque(['Michael', 'Terry', 'Graham'])
列表推導式
列表推導式提供了從序列創建列表的簡單途徑。每個列表推導式都在 for 之後跟一個表達式,然後有零到多個 for 或 if 子句。返回結果是一個根據表達從其後的 for 和 if 上下文環境中生成出來的列表。如果希望表達式推導出一個元組,就必須使用括弧。
可以對每一個元素逐個調用,Python strip() 方法用於移除字元串頭尾指定的字元(默認為空格)或字元序列。
1 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] 2 >>> [weapon.strip() for weapon in freshfruit] 3 ['banana', 'loganberry', 'passion fruit']
一些技巧,round() 方法返回浮點數x的四捨五入值,round() 方法返回浮點數x的四捨五入值,
- x — 數值表達式。
- n — 數值表達式,表示從小數點位數。
1 >>> [3*x for x in vec if x > 3] 2 [12, 18] 3 >>> [3*x for x in vec if x < 2] 4 [] 5 >>> [x*y for x in vec1 for y in vec2] 6 [8, 6, -18, 16, 12, -36, 24, 18, -54] 7 >>> [x+y for x in vec1 for y in vec2] 8 [6, 5, -7, 8, 7, -5, 10, 9, -3] 9 >>> [vec1[i]*vec2[i] for i in range(len(vec1))] 10 [8, 12, -54] 11 >>> [str(round(355/113, i)) for i in range(1, 6)] 12 ['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): ... transposed.append([row[i] for row in matrix]) ... >>> transposed [[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 ... transposed_row = [] ... for row in matrix: ... transposed_row.append(row[i]) ... transposed.append(transposed_row) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
del語句
使用 del 語句可以從一個列表中依索引而不是值來刪除一個元素。這與使用 pop() 返回一個值不同。可以用 del 語句從列表中刪除一個切割,或清空整個列表。
1 >>> a = [-1, 1, 66.25, 333, 333, 1234.5] 2 >>> del a[0] 3 >>> a 4 [1, 66.25, 333, 333, 1234.5] 5 >>> del a[2:4] 6 >>> a 7 [1, 66.25, 1234.5] 8 >>> del a[:] 9 >>> a 10 []
元組和序列
組在輸出時總是有括弧的,以便於正確表達嵌套結構。在輸入時可能有或沒有括弧, 不過括弧通常是必須的。
集合
集合是一個無序不重複元素的集。基本功能包括關係測試和消除重複元素。
可以用大括弧({})創建集合。注意:如果要創建一個空集合,你必須用 set() 而不是 {} ;後者創建一個空的字典。
字典
序列是以連續的整數為索引,與此不同的是,字典以關鍵字為索引,關鍵字可以是任意不可變類型,通常用字元串或數值。理解字典的最佳方式是把它看做無序的鍵=>值對集合。在同一個字典之內,關鍵字必須是互不相同。一對大括弧創建一個空的字典:{}。
構造函數 dict() 直接從鍵值對元組列表中構建字典。如果有固定的模式,列表推導式指定特定的鍵值對:
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
字典推導可以用來創建任意鍵和值的表達式詞典
>>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36}
如果關鍵字只是簡單的字元串,使用關鍵字參數指定鍵值對有時候更方便
>>> dict(sape=4139, guido=4127, jack=4098) {'sape': 4139, 'jack': 4098, 'guido': 4127}
遍歷技巧
在字典中遍歷時,關鍵字和對應的值可以使用 items() 方法同時解讀出來
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v)
在序列中遍歷時,索引位置和對應值可以使用 enumerate() 函數同時得到
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe
同時遍歷兩個或更多的序列,可以使用 zip() 組合
1 >>> questions = ['name', 'quest', 'favorite color'] 2 >>> answers = ['lancelot', 'the holy grail', 'blue'] 3 >>> for q, a in zip(questions, answers): 4 ... print('What is your {0}? It is {1}.'.format(q, a)) 5 ... 6 What is your name? It is lancelot. 7 What is your quest? It is the holy grail. 8 What is your favorite color? It is blue.
format格式化函數
print("網站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com")) # 通過字典設置參數 site = {"name": "菜鳥教程", "url": "www.runoob.com"} print("網站名:{name}, 地址 {url}".format(**site)) # 通過列表索引設置參數 my_list = ['菜鳥教程', 'www.runoob.com'] print("網站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必須的