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