python數據處理之列表、集合、字典推導式

1.列表:

  [expr for item in collection if condition]

  舉例:

>>> result = []
>>> [result.append(item) for item in fruit if len(item) > 5]
[None, None]
>>> result
['banana', 'orange']
  效果與下面類似:
>>> result = []
>>> fruit = ['apple', 'banana', 'orange']
>>> for item in fruit:
...     if len(item)>5:
...         result.append(item)
... 
>>> result
['banana', 'orange']

2.集合:
 (expr for item in collection if condition)  與列表只有外面括號的差別。

!!!多謝下面的指出,集合外面的括號應該是大括號{},即{expr for item in collection if condition}


3.字典:

 {key : value for item in collectio if condition}

 例子:

>>> fruit = ['apple', 'banana', 'orange']
>>> dictresult = {}
>>> dictresult = {key: value for key, value in enumerate(fruit) if len(value) > 5}
>>> dictresult
{1: 'banana', 2: 'orange'}

相同效果:

>>> fruit = ['apple', 'banana', 'orange']
>>> dictresult = {}
>>> for key, value in enumerate(fruit):
...     if len(value) > 5:
...         dictresult[key] = value
... 
>>> dictresult
{1: 'banana', 2: 'orange'}

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