python数据处理之列表、集合、字典推导式

列表

_ [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']

集合

_ (expr for item in collection if condition) _ 与列表只有外面括号的差别。

!!!多谢下面的指出,集合外面的括号应该是大括号{},即{ _ expr for item in collection if condition _ }

字典

_ {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'}

文章作者:Lily

原始链接:/2018/04/08/python%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86%E4%B9%8B%E5%88%97%E8%A1%A8%E3%80%81%E9%9B%86%E5%90%88%E3%80%81%E5%AD%97%E5%85%B8%E6%8E%A8%E5%AF%BC%E5%BC%8F/

版权说明:转载请保留原文链接及作者。