带有判断条件的表达式为
[Expression for target in iterable if condition]
列表推导式实现嵌套的表达式为
[Expression for target1 in iterable 1
for target2 in iterable 2
......
for targetn in iterable n
使用推导式将二维列表降维:
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
[j for i in matrix for j in i]
# 打印结果为
[1, 2, 3, 4, 5, 6, 7, 8, 9]
用嵌套循环的方式写
matrix = [[1,2,3],
[4,5,6],
[7,8,9]]
a = []
for i in matrix:
for j in i:
a.append(j)
print(a)
# 输出结果为
[1, 2, 3, 4, 5, 6, 7, 8, 9] #嵌套循环帮助理解推导式的内容
列表推导式的终极表达式
[Expression for target1 in iterable 1 if condition
for target2 in iterable 2 if condition
......
for targetn in iterable n if condition
举例
for x in range(10):
if x % 2 == 0:
for y in range(10):
if y % 3 == 0:
print([x,y])
# 等同于下面的列表推导式写法
[[x,y] for x in range(10) if x % 2==0 for y in range(10) if y % 3 ==0]
[[0, 0], [0, 3], [0, 6], [0, 9], [2, 0], [2, 3], [2, 6], [2, 9], [4, 0], [4, 3], [4, 6], [4, 9], [6, 0], [6, 3], [6, 6], [6, 9], [8, 0], [8, 3], [8, 6], [8, 9]]