初级列表推导式:[expression for target in Object]
list=[i for i in range(10)]
print(list)
高级列表推导式:(1):[expression target in Object if condition]
(2)[expression for target1 in Object1 for target2 in Object …]
"""第一种"""
list=[i for i in range(11) if i%2==0]
print(list)
"""第二种"""
list=[[i,j] for i in range(3) for j in range(3)]
print(list)
超级列表推导式:[expression for target1 in Object if condition1 for target2 in Object if condition2 …]
list=[[i,j,k] for i in range(3) if i%2==0
for j in range(3) if i%2==0
for k in range(3) if i%2==0]
print(list)
上面的表达式可以灵活运用,这里只是一些简单的例子。
运行结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10]
[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 2, 0], [0, 2, 1], [0, 2, 2], [2, 0, 0], [2, 0, 1], [2, 0, 2], [2, 1, 0], [2, 1, 1], [2, 1, 2], [2, 2, 0], [2, 2, 1], [2, 2, 2]]