【问题标题】:How to look at a for loop within a for loop the pythonic way如何以pythonic方式查看for循环中的for循环
【发布时间】:2020-03-01 23:26:45
【问题描述】:

我从 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 循环执行此操作...我对此很陌生,所以我猜必须有某种方法可以做到这一点,但我没有怎么看。有人怎么做吗?

【问题讨论】:

  • 您可以将一个 for 循环嵌套在另一个循环中,就像在上一个示例中 iffor 内一样。
  • 其实你也得把它们的顺序颠倒一下,所以最后一个变成了第一个for等等
  • 谢谢!那么这对于这个 [x + [y] for x in result for y in pool] 是如何工作的。我不太明白如何以正确的方式附加 x + [y] ...

标签: python for-loop combinations itertools


【解决方案1】:

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

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

【讨论】:

  • 谢谢!那么这对于这个 [x + [y] for x in result for y in pool] 是如何工作的。我不太明白如何以正确的方式附加 x + [y]....
  • @Ablu_68 我已经更新了答案以显示该示例。至于为什么它们以正确的方式附加,那是因为首先,我们有result = [[]],然后我们遍历第一个pool["a","b"])并将其附加到result中的所有内容,给我们[["a"], ["b"]] .然后我们将第二个pool (["a", "c", "d"]) 中的每个元素附加到result 中的每个元素上,得到[["a", "a"], ["a", "c"], ["a", "d"], ["b", "a"], ["b", "c"], ["b", "d"]],依此类推。希望这是有道理的。
  • @Winstone 是的,这正是我想要的!这完全有道理,我现在因为自己没有看到它而感到有点愚蠢.. :) 谢谢!
猜你喜欢
  • 2017-08-17
  • 2011-10-18
  • 2021-10-28
  • 2020-06-08
  • 2011-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多