[英]Python all combinations for multiple lists with variable k
我可以为单个列表生成具有特定值(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,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的所有值组合,请遵循此模式。
让我知道是否不清楚,我可以相应地编辑问题。
您可以单独通过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))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.