列表推導式
列表推導式提供了從序列建立列表的簡單途徑。一般應用程序將一些操做應用於某個序列的每一個元素,用其得到的結果做爲生成新列表的元素,或者根據肯定的斷定條件建立子序列。
每一個列表推導式都在 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)
...
9
7
5
3
1
要按順序遍歷一個序列,使用 sorted() 函數返回一個已排序的序列,並不修改原值:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear