[英]python double for in list comprehension
我检查了其他问题,但在这里我发现了一些很奇怪的东西。
如果我在列表理解中制作两个 for 循环,它会很好地工作。
pools = [(0, 1, 2), (0, 1, 2)]
result = [[]]
for pool in pools:
result = [x + [y] for x in result for y in pool]
# print(result)
# result = [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
但是如果我把它分解成普通的嵌套 for 循环,那将是一个无穷无尽的代码。
pools = [(0, 1, 2), (0, 1, 2)]
result = [[]]
for pool in pools:
for x in result:
for y in pool:
result.append(x + [y])
# This will be an endless looping
我猜这可能是因为 python 列表理解中有一些隐藏代码? 非常感谢您的善意帮助。
我已经修改了嵌套的 for 循环,但似乎仍然不起作用。
pools = [(0, 1, 2), (0, 1, 2)]
result = [[]]
temp = [[]]
for pool in pools:
for x in result:
for y in pool:
temp.append(x + [y])
result = temp
# result = [[], [0], [1], [2], [0], [1], [2]]
在第一个代码示例中,首先执行列表理解,最后创建的列表被分配给result
。
在第二个示例中, result
引用的列表被修改,而第二个 for 循环遍历它。 result
在循环中附加新项以确保 for 循环永远不会耗尽列表。
列表理解可以用传统的 for 循环重写为:
pools = [(0, 1, 2), (0, 1, 2)]
result = [[]]
for pool in pools:
temp = [] # Begin of rewritten list comprehension
for x in result:
for y in pool:
temp.append(x + [y])
result = temp # Final assignment of constructed list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.