这个记忆技巧对我帮助很大:
[< currend_value > < outer_loop1 > < inner_loop2 > < inner_loop3 >…]< OPTIONAL_IF >)
现在你可以考虑返回+外循环
作为唯一的正义秩序
知道了上面,列表综合的顺序即使是3个循环看起来也很简单:
c=[111, 222, 333]
b=[11, 22, 33]
a=[1, 2, 3]
print(
[
(i, j, k) # <RETURNED_VALUE>
for i in a for j in b for k in c # in order: loop1, loop2, loop3
if i < 2 and j < 20 and k < 200 # <OPTIONAL_IF>
]
)
[(1, 11, 111)]
因为上面只是一个:
for i in a: # outer loop1 GOES SECOND
for j in b: # inner loop2 GOES THIRD
for k in c: # inner loop3 GOES FOURTH
if i < 2 and j < 20 and k < 200:
print((i, j, k)) # returned value GOES FIRST
对于迭代一个嵌套的列表/结构,技术是相同的:
对于a这个问题:
a = [[1,2],[3,4]]
[i2 for i1 in a for i2 in i1]
which return [1, 2, 3, 4]
对于另一个嵌套级别
a = [[[1, 2], [3, 4]], [[5, 6], [7, 8, 9]], [[10]]]
[i3 for i1 in a for i2 in i1 for i3 in i2]
which return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
等等