原文链接:http://www.juzicode.com/python-note-list-comprehensions/
1、列表推导
对一个可迭代对象单个元素进行计算,得到新的列表,比如有一个列表[1,2,3,4,5,6,7],要计算各元素的平方后得到一个新的列表,可以用循环的方式:
#vx:桔子code / juzicode.com
a = [1,2,3,4,5,6,7]
x = []
for t in a:
x.append(t**2)
print(x)
运行结果:
[1, 4, 9, 16, 25, 36, 49]
但是我们也可以用更pythonic的列表推导式实现:
#vx:桔子code / juzicode.com
a = [1,2,3,4,5,6,7]
x = [t**2 for t in a]
print(x)
运行结果:
[1, 4, 9, 16, 25, 36, 49]
2、带条件的列表推导
改变下条件,我们可能只需要计算其中的奇数的平方:
#vx:桔子code / juzicode.com
a = [1,2,3,4,5,6,7]
x = []
for t in a:
if t%2==0:
continue
x.append(t**2)
print(x)
运行结果:
[1, 9, 25, 49]
如果用列表推导式,则在推导式中增加条件:
#vx:桔子code / juzicode.com
a = [1,2,3,4,5,6,7]
x = [t**2 for t in a if t%2!=0]
print(x)
运行结果:
[1, 9, 25, 49]
3、多元素列表推导
比如有2个列表[1,2,3,4,5] 和[100,200,300],要求出其所有的组合形式:
#vx:桔子code / juzicode.com
a = [1,2,3,4,5]
b = [100,200,300]
x = [(t1,t2) for t1 in a for t2 in b]
print(x)
运行结果:
[(1, 100), (1, 200), (1, 300), (2, 100), (2, 200), (2, 300), (3, 100), (3, 200), (3, 300), (4, 100), (4, 200), (4, 300), (5, 100), (5, 200), (5, 300)]
加入条件的多元素列表推导:
#vx:桔子code / juzicode.com
a = [1,2,3,4,5]
b = [100,200,300]
x = [(t1,t2) for t1 in a for t2 in b if t1%2!=0 if t2%200!=0]
print(x)
运行结果:
[(1, 100), (1, 300), (3, 100), (3, 300), (5, 100), (5, 300)]
多元素列表推导式顺序差异对比:
#vx:桔子code / juzicode.com
a = [1,3,5]
b = [100,200]
x = [(t1,t2) for t1 in a for t2 in b]#先推a中元素
print(x)
x = [(t1,t2) for t2 in b for t1 in a]#先推b中的元素
print(x)
运行结果:
[(1, 100), (1, 200), (3, 100), (3, 200), (5, 100), (5, 200)]
[(1, 100), (3, 100), (5, 100), (1, 200), (3, 200), (5, 200)]