我从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
并将它们放在新行上):对于问题中的示例,列表理解中的
result
引用了result
的旧值,因此在创建新的result
时需要保留该值:或者,您可以在不同的变量中构建新的
result
,并将result
设置为:还有另一个例子here
相关问题 更多 >
编程相关推荐