如何以python的方式看待for循环中的for循环

2024-06-17 13:27:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我从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循环做到这一点。。。我对这个很陌生,所以我猜一定有办法做到这一点,但我不知道怎么做。有人知道怎么做吗


Tags: 方法代码in列表forif方式args
1条回答
网友
1楼 · 发布于 2024-06-17 13:27:43

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

[(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]

相当于(通过取每个forif并将它们放在新行上):

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

还有另一个例子here

相关问题 更多 >