简体   繁体   English

Python的所有组合具有变量k的多个列表

[英]Python all combinations for multiple lists with variable k

I am able to produce all combinations given a particular value (k) for a single list as follows: 我可以为单个列表生成具有特定值(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

Note, in this code, k requires a specific value to be inputted - it cannot be a variable. 注意,在此代码中,k要求输入一个特定值-它不能是变量。

However, I now have multiple lists in which I need all combinations for various k: 但是,我现在有多个列表,其中需要各种k的所有组合:

m = [1, 2, 3, 4]
t = [1, 2, 3, 4]
c = [1, 2, 3, 4, 5]
ss =[1, 2, 3]

Put simply: I require an output of all the combinations possible for all these lists. 简而言之:我需要所有这些列表可能的所有组合的输出。 Eg k = 1 through 4 for m and t, 1 through 5 for c, and 1 through 3 for ss. 例如,对于m和t,k = 1至4,对于c,1至5,对于ss为1至3。

Example of k = 2 for ss would be 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]

Follow this pattern for all values combinations of k possible in all variables. 对于所有变量中k的所有值组合,请遵循此模式。

Let me know if this is unclear and I can edit question accordingly. 让我知道是否不清楚,我可以相应地编辑问题。

You can get your output via itertools.product alone or via combinations . 您可以单独通过itertools.product或通过combinations获得输出。 We could cram this all into one line if we really wanted, but I think it's more comprehensible to write 如果我们确实愿意,我们可以将所有内容都塞进一行,但是我认为写起来更容易理解

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

after which we have 之后我们有

>>> 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

which is the right number of results: 正确的结果数:

>>> (2**4 - 1) * (2**4 - 1) * (2**5-1) * (2**3 - 1)
48825

and hits every possibility: 并击中各种可能性:

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM