在 python 中将此单行嵌套 for 循环转换为多行

Convert this single-line nested for loop to multi-line in python

我无法理解我在这里修改的代码有何不同。第一部分来自python documentation.

def product(*args, **kwds):
    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)

我想制作一段非常相似的代码,但有条件限制我们何时实际为参数中的特定元素取乘积,所以我想将行 result = [x+[y] for x in result for y in pool] 转换为多行,然后我可以使用我的 if 语句等。这是我所做的,但是当我 运行 它时,它似乎陷入了无限循环,或者什么的...

def Myproduct(*args, **kwds):
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        for x in result:
            for y in pool:
                result.append(x+[y])
    for prod in result:
        yield tuple(prod)

我想真正了解这里的区别。我已经通读并认为我得到 this post,但我仍然没有看到在这种情况下如何正确转换,或者至少为什么它不是相同的转换。提前谢谢你。

问题是您要添加到正在迭代的列表中。因此,如果一开始是 result = [[]]pools = [1, 2, 3],那么在 for x in result 的第一次迭代之后,您的列表将是 [[], [] + [1]],那么您将获取第二个元素,依此类推.

列表理解是在一行中创建一个新列表,然后将其重命名以映射到结果。

修改要迭代的列表时要非常小心!

这是一个等效函数:

def myproduct(*args, **kwds):
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        nresult = []
        for x in result:
            for y in pool:
                nresult.append(x+[y])
        result = nresult
    for prod in result:
        yield tuple(prod)

请注意,创建 nresult 是为了避免 指出的问题。