[英]python list comprehension doesn't work when converted to nested for loops
我正在嘗試從itertools庫了解此代碼段
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
該函數的作用是接受兩個參數:一組字符和輸出的長度,然后使用給定的一組字符生成所有可能的排列。 例如:
product('ab', repeat=3)
#produces
['a','a','a'],
['a','a','b'],
['a','b','a'],
['a','b','b'],
['b','a','a'],
['b','a','b'],
['b','b','a'],
['b','b','b']
除了這一行外,所有這些對我來說都是有意義的:
for pool in pools:
result = [x+[y] for x in result for y in pool]
我試圖將其壓縮為正常的循環:
for pool in pools:
for x in result:
for y in pool:
result.append(x+[y])
但是我最終陷入了無限循環!
它是如何工作的?
這部分是列表理解 。 您翻譯正確。 但在
for pool in pools:
result = [x+[y] for x in result for y in pool]
您可以使用result
和pool
創建一個列表,然后將其分配給result
。
在
for pool in pools:
for x in result:
for y in pool:
result.append(x+[y])
您遍歷result( for x in result
result for x in result
),並向其中添加元素,因此它一直在增長。
如果要創建for循環,可以使用一個臨時變量來保存先前的result
,並構建新的result
:
for pool in pools:
result2 = result[:]
result = []
for x in result2:
for y in pool:
result.append(x+[y])
編輯:感謝@razzak和@GregHewgill糾正了我的錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.