迭代
如果給定一個 list 或 tuple,我們可以通過 for 循環來遍歷這個 list 或
tuple,這種遍歷我們稱爲迭代。Python 的 for 循環不僅可以用在 list 或 tuple 上,還可以作用在其他可迭代對象上。list 這種數據類型雖然有下標,但很多其他數據類型是沒有下標的,但是,只要是可迭代對象,無論有無下標,都可以迭代,比如 dict 就可以迭代:
>>> d = {'a':1,'b':2,'c':3}
>>> for i in d:
print(i)
因爲 dict 的存儲不是按照 list 的方式順序排列,所以,迭代出的結果順
序很可能不一樣。
所以,當我們使用 for 循環時,只要作用於一個可迭代對象,for 循環
就可以正常運行,而我們不太關心該對象究竟是 list 還是其他數據類型。
那麼,如何判斷一個對象是可迭代對象呢?方法是通過 collections 模塊
的 Iterable 類型判斷:
>>> from collections.abc import Iterable
>>> isinstance('abc',Iterable)
True
>>> isinstance([1,2,3],Iterable)
True
>>> isinstance(123,Iterable)
False
Python 內置的 enumerate 函數可以把一個 list 變成索引-元素對,這樣就
可以在 for 循環中同時迭代索引和元素本身:
>>> for i,value in enumerate(['a','b','c']):
print(i,value)
輸出結果:
0 a
1 b
2 c
列表生成式
列表生成式即 List Comprehensions,是 Python 內置的非常簡單卻強大的
可以用來創建 list 的生成式。舉個例子,要生成 list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用 list(range(1, 11)):
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
如果要得到x2的列表,則:
>>> for i in range(1,11):
L.append(i * i)
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
但是循環太繁瑣,而列表生成式則可以用一行語句代替循環生成上面的
list:
>>> [x * x for x in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
還可以增加一個判斷條件:
>>> [x * x for x in range(1,11) if x % 4 == 0]
[16, 64]
還可以使用兩層循環,可以生成全排列:
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
列出當前目錄下的所有文件和目錄名,可以通過一行代碼實現:
>>> import os
>>> [d for d in os.listdir('.')]
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']
如果 list 中既包含字符串,又包含整數,由於非字符串類型沒有 lower()
方法,所以列表生成式會報錯:
>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s in L]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'
使用內建的 isinstance 函數可以判斷一個變量是不是字符串:
>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False
請修改列表生成式,通過添加 if 語句保證列表生成式能正確地執行:
>>> list = ['Hello','World',18,'Apple',None]
>>> [s.lower() for s in list if isinstance(s,str)]
['hello', 'world', 'apple']
運用列表生成式,可以快速生成list,可以通過一個list推導出另一個list,
而代碼卻十分簡潔。