Python 列表生成式(List Comprehensions)

轉自http://blog.csdn.net/yizheyouye/article/details/50638895

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

但是如果要生成[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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

但是循環太繁瑣,而列表生成器則可以用一行語句代替循環生成上面的list:

>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  • 1
  • 2

寫列表生成式時,把要生成元素x * x放在前面,後面跟for循環,就可以把list創建出來,十分有用,多謝幾次,很快就可以熟悉這種寫法。

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

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

還可以使用兩層循環,可以生成全排列:

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

三層和三層以上的循環就很少用到了。 
這裏寫圖片描述

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

>>> 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']
  • 1
  • 2
  • 3

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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

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

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

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

這裏寫圖片描述
這裏寫圖片描述

小練習:

如果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'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

使用內建的isinstance函數可以判斷一個變量是不是字符串:

>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

請修改列表生成式,通過添加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']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

這裏寫圖片描述


發佈了10 篇原創文章 · 獲贊 67 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章