Python數據結構

 列表

Python中列表是可變的,這是它區別於字符串和元組的最重要的特色,一句話歸納即:列表能夠修改,而字符串和元組不能。如下是 Python 中列表的方法:
 
 
 下面示例演示了列表的大部分方法:

>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print(a.count(333), a.count(66.25), a.count('x'))
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
注意:相似 insert, remove 或 sort 等修改列表的方法沒有返回值。
 
  將列表當作堆棧使用

列表方法使得列表能夠很方便的做爲一個堆棧來使用,堆棧做爲特定的數據結構,最早進入的元素最後一個被釋放(後進先出)。用 append() 方法能夠把一個元素添加到堆棧頂。用不指定索引的 pop() 方法能夠把一個元素從堆棧頂釋放出來。例如:

>>> stack = [3, 4, 5] 
>>> stack.append(6) 
>>> stack.append(7) 
>>> stack
 [3, 4, 5, 6, 7] 
>>> stack.pop() 
>>> stack [3, 4, 5, 6] 
>>> stack.pop() 
>>> stack.pop() 
>>> stack 
[3, 4]
 
 將列表看成隊列使用

也能夠把列表當作隊列用,只是在隊列裏第一加入的元素,第一個取出來;可是拿列表用做這樣的目的效率不高。在列表的最後添加或者彈出元素速度快,然而在列表裏插入或者從頭部彈出速度卻不快(由於全部其餘的元素都得一個一個地移動)。


  >>> 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'])
 
 
 列表推導式

列表推導式提供了從序列建立列表的簡單途徑。一般應用程序將一些操做應用於某個序列的每一個元素,用其得到的結果做爲生成新列表的元素,或者根據肯定的斷定條件建立子序列。

每一個列表推導式都在 for 以後跟一個表達式,而後有零到多個 for 或 if 子句。返回結果是一個根據表達從其後的 for 和 if 上下文環境中生成出來的列表。若是但願表達式推導出一個元組,就必須使用括號。

這裏咱們將列表中每一個數值乘三,得到一個新的列表:

>>> vec = [2, 4, 6] 
>>> [3*x for x in vec] 
[6, 12, 18]
如今咱們玩一點小花樣:
>>> [[x, x**2] for x in vec] 
[[2, 4], [4, 16], [6, 36]]
這裏咱們對序列裏每個元素逐個調用某方法:
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] 
>>> [weapon.strip() for weapon in freshfruit] 
['banana', 'loganberry', 'passion fruit']
咱們能夠用 if 子句做爲過濾器:
>>> [3*x for x in vec if x > 3] 
[12, 18] 
>>> [3*x for x in vec if x < 2] 
[]
如下是一些關於循環和其它技巧的演示:
>>> vec1 = [2, 4, 6] 
>>> vec2 = [4, 3, -9] 
>>> [x*y for x in vec1 for y in vec2]
 [8, 6, -18, 16, 12, -36, 24, 18, -54] 
>>> [x+y for x in vec1 for y in vec2]
 [6, 5, -7, 8, 7, -5, 10, 9, -3] 
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
 [8, 12, -54]
列表推導式可使用複雜表達式或嵌套函數:
>>> [str(round(355/113, i)) for i in range(1, 6)] 
['3.1', '3.14', '3.142', '3.1416', '3.14159']

嵌套列表解析

Python的列表還能夠嵌套。如下實例展現了3X4的矩陣列表:

>>> matrix = [ 
... [1, 2, 3, 4], 
... [5, 6, 7, 8], 
... [9, 10, 11, 12], 
... ]
如下實例將3X4的矩陣列表轉換爲4X3列表:
>>> [[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 語句從列表中刪除一個切割,或清空整個列表(咱們之前介紹的方法是給該切割賦一個空列表)。例如: 
>>> 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 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))

如你所見,元組在輸出時老是有括號的,以便於正確表達嵌套結構。在輸入時可能有或沒有括號, 不過括號一般是必須的(若是元組是更大的表達式的一部分)。

集合

集合是一個無序不重複元素的集。基本功能包括關係測試和消除重複元素。

能夠用大括號({})建立集合。注意:若是要建立一個空集合,你必須用 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 either a or b 
{'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'}
>>> 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 either a or b 
{'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'}
 
 字典

另外一個很是有用的 Python 內建數據類型是字典。

序列是以連續的整數爲索引,與此不一樣的是,字典以關鍵字爲索引,關鍵字能夠是任意不可變類型,一般用字符串或數值。

理解字典的最佳方式是把它看作無序的鍵=>值對集合。在同一個字典以內,關鍵字必須是互不相同。

一對大括號建立一個空的字典:{}。

這是一個字典運用的簡單例子:

>>> tel = {'jack': 4098, 'sape': 4139} 
>>> tel['guido'] = 4127 
>>> tel 
{'sape': 4139, 'guido': 4127, 'jack': 4098} 
>>> tel['jack'] 
4098 
>>> del tel['sape'] 
>>> tel['irv'] = 4127 
>>> tel 
{'guido': 4127, 'irv': 4127, 'jack': 4098} 
>>> list(tel.keys()) 
['irv', 'guido', 'jack'] 
>>> sorted(tel.keys())
 ['guido', 'irv', 'jack'] 
>>> 'guido' in tel 
True 
>>> 'jack' not in tel 
False

構造函數 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) 
... 
gallahad the pure 
robin the brave

在序列中遍歷時,索引位置和對應值可使用 enumerate() 函數同時獲得:

>>> for i, v in enumerate(['tic', 'tac', 'toe']): 
...   print(i, v) 
... 
0 tic 
1 tac 
2 toe
同時遍歷兩個或更多的序列,可使用 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.

要反向遍歷一個序列,首先指定這個序列,而後調用 reversesd() 函數:

>>> for i in reversed(range(1, 10, 2)): 
... print(i) 
... 
1

要按順序遍歷一個序列,使用 sorted() 函數返回一個已排序的序列,並不修改原值:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] 
>>> for f in sorted(set(basket)): 
...   print(f) 
... 
apple
banana 
orange 
pear
相關文章
相關標籤/搜索