【发布时间】: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 循环嵌套在另一个循环中,就像在上一个示例中
if在for内一样。 -
其实你也得把它们的顺序颠倒一下,所以最后一个变成了第一个
for等等 -
谢谢!那么这对于这个 [x + [y] for x in result for y in pool] 是如何工作的。我不太明白如何以正确的方式附加 x + [y] ...
标签: python for-loop combinations itertools