1. 程式人生 > 實用技巧 >python菜鳥教程學習10:資料結構

python菜鳥教程學習10:資料結構

列表方法

  • 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" 是必須的