# python中的推导式使用详解

1.列表推导式
2.字典推导式
3.集合推导式

note: 字典和集合推导是最近才加入到python的(python 2.7 和python 3.1以上版). 下面简要介绍下:

【列表推导式】

[expr for value in collection ifcondition]

result = []
for value in collection:
if condition:
result.append(expression)

>>> names = [‘bob’,’tom’,’alice’,’jerry’,’wendy’,’smith’]

>>> [name.upper() for name in names if len(name)>3]
[‘alice’, ‘jerry’, ‘wendy’, ‘smith’]

>>> [(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1]
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]

>>> m = [[1,2,3],
… [4,5,6],
… [7,8,9]]
>>> m
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [row[2] for row in m]
[3, 6, 9]

#或者用下面的方式
>>> [m[row][2] for row in (0,1,2)]
[3, 6, 9]

>>> m
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [m[i][i] for i in range(len(m))]
[1, 5, 9]

>>> m = [[1,2,3],
… [4,5,6],
… [7,8,9]]
>>> n = [[2,2,2],
… [3,3,3],
… [4,4,4]]
>>> [m[row][col]*n[row][col] for row in range(3) for col in range(3)]
[2, 4, 6, 12, 15, 18, 28, 32, 36]
>>> [[m[row][col]*n[row][col] for col in range(3)] for row in range(3)]
[[2, 4, 6], [12, 15, 18], [28, 32, 36]]
>>> [[m[row][col]*n[row][col] for row in range(3)] for col in range(3)]
[[2, 12, 28], [4, 15, 32], [6, 18, 36]]

>>> bob
{‘pay’: 3000, ‘job’: ‘dev’, ‘age’: 42, ‘name’: ‘bob smith’}
>>> sue
{‘pay’: 4000, ‘job’: ‘hdw’, ‘age’: 45, ‘name’: ‘sue jones’}
>>> people = [bob, sue]
>>> [rec[‘age’]+100 if rec[‘age’] >= 45 else rec[‘age’] for rec in people] # 注意for位置
[42, 145]

【字典推导式】

{ key_expr: value_expr for value in collection if condition }

>>> strings = [‘import’,’is’,’with’,’if’,’file’,’exception’]

>>> d = {key: val for val,key in enumerate(strings)}

>>> d
{‘exception’: 5, ‘is’: 1, ‘file’: 4, ‘import’: 0, ‘with’: 2, ‘if’: 3}

【集合推导式】

{ expr for value in collection if condition }

>>> strings = [‘a’,’is’,’with’,’if’,’file’,’exception’]
>>> {len(s) for s in strings} #有长度相同的会只留一个，这在实际上也非常有用
set([1, 2, 4, 9])

【嵌套列表推导式】

>>> l = [[1,2,3],
[4,5,6],
[7,8,9]]

names = [[‘tom’,’billy’,’jefferson’,’andrew’,’wesley’,’steven’,’joe’],
[‘alice’,’jill’,’ana’,’wendy’,’jennifer’,’sherry’,’eva’]]

tmp = []
for lst in names:
for name in lst:
if name.count(‘e’) >= 2:
tmp.append(name)

print tmp
#输出结果
>>>
[‘jefferson’, ‘wesley’, ‘steven’, ‘jennifer’]

>>> names = [[‘tom’,’billy’,’jefferson’,’andrew’,’wesley’,’steven’,’joe’],
[‘alice’,’jill’,’ana’,’wendy’,’jennifer’,’sherry’,’eva’]]

>>> [name for lst in names for name in lst if name.count(‘e’)>=2] #注意遍历顺序，这是实现的关键
[‘jefferson’, ‘wesley’, ‘steven’, ‘jennifer’]