#python入門5#高級特性--列表生成式

列表生成式即List Comprehensions,是Python內置的非常簡單卻強大的可以用來創建list的生成式

  1. 例如生成[1,2,3,4,5,6,7,8,9,10]:
  >>> list(range(1,11))
  [1,2,3,4,5,6,7,8,9,10]
  1. 生成[11, 22, 33, ..., 1010]:
  >>> [x*x for x in range(1,11)]
  [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

寫列表生成式時,把要生成的元素x * x放到前面,后面跟for循環,就可以把list創建出來

  1. for循環后面還可以加上if判斷,這樣我們就可以篩選出僅偶數的平方:
  >>> [x*x for x in range(1, 11) if x%2 ==0 ]
  [4,16,36, 64, 100]
  1. 還可以使用兩層循環,可以生成全排列
  >>> [m+n for m in 'abc' for n in 'xyz']
  ['ax', 'ay', 'az', 'bx', 'by', 'bz', 'cx', 'cy', 'cz']
  1. 列出當前目錄下的所有文件和目錄名,可以通過一行代碼實現
  >>> import os # 導入os模塊
  >>> [d for d in os.listdir('.')]
  ['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']
  1. 列表生成式也可以使用2個變量來生成list:
  >>> d={'x':'a',  'y':'b',  'z':'c'}
  >>> [ k+ '=' + v for k,v in d.items()]
 ['y=b', 'x=a', 'z=c']
  1. 把list中的所有字符串變成小寫
  >>> L=['Hello', 'World', 'IBM', 'Apple']
  >>> [s.lower() for s in L]
  ['hello', 'world', 'ibm', 'apple']
  1. 若list中含有字符串,數字,則可以:
  >>> L = ['Hello', 'World', 18, 'Apple']
  >>> [d.lower() for d in L if isinstance(d, str)]
  ['hello', 'world', 'apple']
學習來源于廖雪峰教程
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容