我通常在脑海中将其展开为一个生成循环,例如
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
是生成器的列表理解
for x in [1,2,3]: for y in [3,1,4]: if x != y: yield (x, y)
例子1
[x for b in a for x in b]是对
for b in a: for x in b: yield x
结果示例
a = [[1,2,3],[4,5,6]]:
[1, 2, 3, 4, 5, 6]
范例#2
[[row[i] for row in matrix] for i in range(4)](请注意,内部表达式是另一种理解!):
for i in range(4): yield [row[i] for row in matrix]
展开了
for i in range(4): l = [] for row in matrix: l.append(row[i]) yield l
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)