简体   繁体   English

转换为嵌套的for循环时,python list comprehension不起作用

[英]python list comprehension doesn't work when converted to nested for loops

I'm trying to understand this snippet from itertools library 我正在尝试从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)

What this function does is that it takes two arguments: a set of characters and a length of the output, then generates all possible permutations using the given set of characters. 该函数的作用是接受两个参数:一组字符和输出的长度,然后使用给定的一组字符生成所有可能的排列。 for example: 例如:

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']

all make sense to me except for this line: 除了这一行外,所有这些对我来说都是有意义的:

for pool in pools:
    result = [x+[y] for x in result for y in pool]

i tried to uncompact it to normal for loops: 我试图将其压缩为正常的循环:

for pool in pools:
    for x in result:
        for y in pool:
            result.append(x+[y])

But i ended up with infinite loop! 但是我最终陷入了无限循环!

How does it work? 它是如何工作的?

This part is a list comprehension . 这部分是列表理解 You got the translation right. 您翻译正确。 But in 但在

for pool in pools:
    result = [x+[y] for x in result for y in pool]

you create a list, using result and pool , and then assign it to result . 您可以使用resultpool创建一个列表,然后将其分配给result

In

for pool in pools:
    for x in result:
        for y in pool:
            result.append(x+[y])

you iterate over result ( for x in result ), and add elements to it, so it keeps growing. 您遍历result( for x in result result for x in result ),并向其中添加元素,因此它一直在增长。

If you want to create for loops, you can use a temporary variable to save the previous result , and build the new one: 如果要创建for循环,可以使用一个临时变量来保存先前的result ,并构建新的result

for pool in pools:
    result2 = result[:]
    result = []
    for x in result2:
        for y in pool:
            result.append(x+[y])

Edit: Thanks to @razzak and @GregHewgill for correcting my mistakes 编辑:感谢@razzak和@GregHewgill纠正了我的错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM