首页 > 解决方案 > 如何以pythonic方式查看for循环中的for循环

问题描述

我从 itertools.product 中找到了这段代码来查找列表的唯一组合

args = [["a","b"], ["a", "c", "d"], ["h"]]
pools = [tuple(pool) for pool in args]

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

这使:

print(result)
[['a', 'a', 'h'], ['a', 'c', 'h'], ['a', 'd', 'h'], ['b', 'a', 'h'], ['b', 'c', 'h'], ['b', 'd', 'h']]

现在我想知道是否有一种方法可以使用 for 循环以“正常”方式编写它?我设法使用 if 语句将其重写为单个 for 循环,如下所示:

[s for s in p if s != 'a']

等于:

s = []
for x in p:
    if x != 1:
        s.append(x)

但是我还没有设法在 for 循环中为 for 循环执行此操作...我对此很陌生,所以我猜必须有某种方法可以做到这一点,但我不知道如何做。有谁怎么做到这一点?

标签: pythonfor-loopcombinationsitertools

解决方案


我认为你可以继续这个趋势,例如:

[(x,y) for x in [0,1,2,3,4,5] if x < 3 for y in [0,1,2,3,4,5] if 2 < y if x + y == 4]

等效于(通过将每个forandif放在一个新行上):

s = []
for x in [0,1,2,3,4,5]:
    if x < 3:
        for y in [0,1,2,3,4,5]:
            if 2 < y:
                if x + y == 4:
                    s.append((x,y))

对于问题中的示例,result列表理解内部指的是 的旧值result,因此在创建新值时需要保留该值result

result = [[]]
for pool in pools:
    old_result = result # remember the old result
    result = [] # build the new result with this variable
    for x in old_result:
        for y in pool:
            result.append(x + [y])

result或者,您可以在不同的变量中构建新变量并将其设置result为:

result = [[]]
for pool in pools:
    new_result = [] # build the new result with this variable
    for x in result:
        for y in pool:
            new_result.append(x + [y])
    result = new_result # update our current result

这里还有另一个例子。


推荐阅读