[英]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.