我可以为单个列表生成给定特定值(k)的所有组合,如下所示:
lst = []
p = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
c = itertools.combinations(p, k)
for i in c:
lst.append(list(i))
print lst
注意,在此代码中,k需要输入特定值 - 它不能是变量。
但是,我现在有多个列表,其中我需要各种k的所有组合:
m = [1, 2, 3, 4]
t = [1, 2, 3, 4]
c = [1, 2, 3, 4, 5]
ss =[1, 2, 3]
简单地说:我需要为所有这些列表输出所有可能的组合。例如。对于m和t,k = 1到4,对于c,k = 1到5,对于ss,1到3。
ss的k = 2的例子是
m = [1, 2, 3, 4]
t = [1, 2, 3, 4]
c = [1, 2, 3, 4, 5]
ss = [1, 2]
m = [1, 2, 3, 4]
t = [1, 2, 3, 4]
c = [1, 2, 3, 4, 5]
ss = [1, 3]
m = [1, 2, 3, 4]
t = [1, 2, 3, 4]
c = [1, 2, 3, 4, 5]
ss = [2, 3]
对所有变量中k的所有值组合遵循此模式。
如果不清楚,请告诉我,我可以相应地编辑问题。
答案 0 :(得分:1)
您可以单独通过itertools.product
或通过combinations
获取输出。如果我们真的想要的话,我们可以将这一切都塞进一行,但我认为编写更容易理解
from itertools import combinations, product
def all_subs(seq):
for i in range(1, len(seq)+1):
for c in combinations(seq, i):
yield c
之后我们
>>> m,t,c,ss = [1,2,3,4],[1,2,3,4],[1,2,3,4,5],[1,2,3]
>>> seqs = m,t,c,ss
>>> out = list(product(*map(all_subs, seqs)))
>>> len(out)
48825
这是正确的结果数量:
>>> (2**4 - 1) * (2**4 - 1) * (2**5-1) * (2**3 - 1)
48825
并点击各种可能性:
>>> import pprint
>>> pprint.pprint(out[:4])
[((1,), (1,), (1,), (1,)),
((1,), (1,), (1,), (2,)),
((1,), (1,), (1,), (3,)),
((1,), (1,), (1,), (1, 2))]
>>> pprint.pprint(out[-4:])
[((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4, 5), (1, 2)),
((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4, 5), (1, 3)),
((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4, 5), (2, 3)),
((1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4, 5), (1, 2, 3))]