推导式comprehensions(又称解析式),是Python的一种独有特性。推导式是可以从一个数据序列构建另一个新的数据序列的结构体。共有三种推导式,在Python2和3中都有支持:
基本格式:
variable = [out_exp_res for out_exp in input_list if out_exp == 2]
实例:
names = ['Bob','Tom','alice','Jerry','Wendy','Smith']
[name.upper() for name in names if len(name)>3]
# ['ALICE', 'JERRY', 'WENDY', 'SMITH']
["%02d:%02d"%(h,m) for h in range(0, 24) for m in range(0, 60, 5)]
[(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]]
[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))] # 打印M[0][0], M[1][1], M[2][2]
# [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]
multiples = [i for i in range(30) if i%3 == 0]
print(multiples)
# Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
def squared(x):
return x*x
multiples = [squared(i) for i in range(30) if i%3 == 0]
print(multiples)
# Output: [0, 9, 36, 81, 144, 225, 324, 441, 576, 729]
将上述两表推导式的[]改成(),即可得到生成器。
multiples = (i for i in range(30) if i%3 == 0)
print(type(multiples))
# Output: <type 'generator'>
字典推导和列表推导的使用类似,只不过中括号改成大括号。
基本格式:{ 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, 'file': 4, 'if': 3, 'import': 0, 'is': 1, 'with': 2}
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
mcase_frequency = {
k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0)
for k in mcase.keys()
if k.lower() in ['a','b']
}
print(mcase_frequency)
# Output: {'a': 17, 'b': 34}
mcase = {'a': 10, 'b': 34}
mcase_frequency = {v: k for k, v in mcase.items()}
print(mcase_frequency)
# Output: {10: 'a', 34: 'b'}
集合推导式跟列表推导式也是类似的。 唯一的区别在于它使用大括号{ }。
基本格式:{ expr for value in collection if condition }
举例说明:
squared = {x**2 for x in [1, 1, 2]}
print(squared)
# Output: set([1, 4])
strings = ['a','is','with','if','file','exception']
{len(s) for s in strings} # 有长度相同的会只留一个,这在实际上也非常有用
# {1, 2, 4, 9}
names = [['Tom','Billy','Jefferson','Andrew','Wesley','Steven','Joe'], ['Alice','Jill','Ana','Wendy','Jennifer','Sherry','Eva']]
tmp = []
# 用for循环实现
for lst in names:
for name in lst:
if name.count('e') >= 2:
tmp.append(name)
print(tmp)
# 用嵌套列表实现
[name for lst in names for name in lst if name.count('e')>=2] # 注意遍历顺序,这是实现的关键
# ['Jefferson', 'Wesley', 'Steven', 'Jennifer']
http://blog.51cto.com/6226001001/2059536