我一直试图在不同列表中找到元素的所有组合。
我尝试使用itertools.product(),但是得到了固定长度的输出列表
import itertools
a=[2,4,6,8,10]
b=[3,6,9]
c=[5,10]
d=[10]
l=list(itertools.product(a,b,c,d))
print(l)
[(2, 3, 5, 10), (2, 3, 10, 10), (2, 6, 5, 10), (2, 6, 10, 10), (2, 9, 5, 10), (2, 9, 10, 10), (4, 3, 5, 10), (4, 3, 10, 10), (4, 6, 5, 10), (4, 6, 10, 10), (4, 9, 5, 10), (4, 9, 10, 10), (6, 3, 5, 10), (6, 3, 10, 10), (6, 6, 5, 10), (6, 6, 10, 10), (6, 9, 5, 10), (6, 9, 10, 10), (8, 3, 5, 10), (8, 3, 10, 10), (8, 6, 5, 10), (8, 6, 10, 10), (8, 9, 5, 10), (8, 9, 10, 10), (10, 3, 5, 10), (10, 3, 10, 10), (10, 6, 5, 10), (10, 6, 10, 10), (10, 9, 5, 10), (10, 9, 10, 10)]
但是我需要的是输出具有不同长度和组合的列表,例如
Expected output : [2,3,5,10],
[2,3,5],
[2,3,10],
[2,3,10,10],
[2,3],
[2,6,5,10],
[2,6,10,10],
[2,6,5],
[2,6],
[2,9,5,10],
[2,9,5],
[2,9],
[2,9,10,10],
[4,3,5,10],
[4,3,5],
[4,3,10,10],
.
.
[10,9,10,10]
...so on
我尝试通过组合所有列表来使用组合,但未提供所需的输出
a=[2,4,6,8,10,3,6,9,5,10]
import itertools
for i in range(1,4):
b=list(itertools.combinations(a,i))
print(b)
鉴于您不知道将获得多少列表作为输入,那么实现预期输出的有效方法是什么?
答案 0 :(得分:2)
您的目标是从每个列表中选择一个元素或不选择元素,对吧?因此,将None
(或其他任何非出现的值)附加到每个列表中,运行itertools.product()
,并从每个结果中删除None
。完成。
>>> raw = itertools.product(a+[None], b+[None], c+[None])
>>> clean = [ [ e for e in result if e is not None ] for result in raw ]
>>> clean[:10]
[[2, 3, 10], [2, 3], [2, 6, 5], [2, 6, 10], [2, 6], [2, 9, 5], [2, 9, 10], [2, 9],
[2, 5], [2, 10]]