1. 程式人生 > >Python教程學習簡記5--Python 列表生成式(List Comprehensions)

Python教程學習簡記5--Python 列表生成式(List Comprehensions)

列表生成式即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]

但是如果要生成[1*1, 2*2 ,3*3, …, 10*10]怎麼做?
方法一是迴圈:

>>> L = []
>>> for x in range(1,11):
...     L.append(x * x)
...
>>> 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迴圈,就可以把list創建出來,十分有用,多謝幾次,很快就可以熟悉這種寫法。

for迴圈後面還可以加上if判斷,這樣我們就可以篩選出僅偶數的平方:

>>> [x * x for
x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100]

還可以使用兩層迴圈,可以生成全排列:

>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

三層和三層以上的迴圈就很少用到了。
這裡寫圖片描述

運用列表生成式,可以寫出非常簡潔的程式碼。例如,列出當前目錄下的所有檔案和目錄名,可以通過一行程式碼實現:

>>> import os # 匯入os模組,後面會講到模組的概念
>>> [d for d in os.listdir('.')] # os.listdir可以列出檔案和目錄 ['.sudo_as_admin_successful', '.gconf', '下載', '.watershed', 'FeelUOwn', '.macromedia', '.node_repl_history', '視訊', '桌面', '.gitconfig', '.vim', '圖片', '.xsession-errors.old', '音樂', '.vim_old', '.pki', 'examples.desktop', '.bashrc~', '.bash_history', '.vimrc_old', '.FeelUOwn', '.cache', '.ssh', '.kingsoft', '公共的', '.dbus', '.xinputrc', '.python_history', '.gemrc', '.profile', '.config', '.gvfs', '.oracle_jre_usage', '.dmrc', '.presage', '.pam_environment', 'hjrblog', '.bashrc', '.ICEauthority', '.adobe', '.viminfo', '.xsession-errors', '.apport-ignore.xml', '.Xauthority', '.mozilla', '文件', '.vimrc', '.local', '.gstreamer-0.10', '模板', '.bash_logout', '.nvm', '.npm']

for迴圈其實可以同時使用兩個甚至多個變數,比如dict的items()可以同時迭代key和value:

>>> d = {'x':'A', 'y':'B', 'z':'C'}
>>> for k, v in d.items():
...     print(k, '=', v)
... 
z = C
y = B
x = A

因此,列表生成式也可以使用兩個變數來生成list:

>>> d = {'x':'A', 'y':'B', 'z':'C'}
>>> [k + '=' + v for k, v in d.items()]
['z=C', 'y=B', 'x=A']

最後把一個list中所有的字串變成小寫:

>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']

這裡寫圖片描述
這裡寫圖片描述

小練習:

如果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語句保證列表生成式能正確地執行:

>>> L1 = ['Hello', 'World', 18, 'Apple', 'None']
>>> [s.lower() for s in L1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'

>>> L2 = [s.lower() for s in L1 if isinstance(s, str)]
>>> L2
['hello', 'world', 'apple', 'none']

這裡寫圖片描述