Python 有没有一种有效的方法可以只获取列表的K个组合?

Python 有没有一种有效的方法可以只获取列表的K个组合?,python,algorithm,Python,Algorithm,假设我有一个从1到8的简单列表,只需要包含7个字符的组合。我怎样才能有效地做到这一点?是否可以在不迭代整个列表的情况下执行此操作 例如,这将不包括整个列表: import itertools stuff = [1, 2, 3,4,5,6,7,8] count = 0 for L in range(0, len(stuff)+1): for subset in itertools.combinations(stuff, L): print(subset) c

假设我有一个从1到8的简单列表,只需要包含7个字符的组合。我怎样才能有效地做到这一点?是否可以在不迭代整个列表的情况下执行此操作

例如,这将不包括整个列表:

import itertools
stuff = [1, 2, 3,4,5,6,7,8]
count = 0
for L in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        print(subset)
        count = count + 1
print count #returns 256 results with 8 matching the 7 length
如果您将
itertools.combinations(stuff,L):
中的L更改为7,那么它可以工作,但会给您提供大量重复的结果(72个结果,大多数是重复的)。我知道我可以从上面的代码中提取我想要的7项,但是对于较大的列表,这样做似乎效率低下。有什么建议吗

在这种情况下,我想要的最终结果是:

(1, 2, 3, 4, 5, 6, 7)
(1, 2, 3, 4, 5, 6, 8)
(1, 2, 3, 4, 5, 7, 8)
(1, 2, 3, 4, 6, 7, 8)
(1, 2, 3, 5, 6, 7, 8)
(1, 2, 4, 5, 6, 7, 8)
(1, 3, 4, 5, 6, 7, 8)
(2, 3, 4, 5, 6, 7, 8)

itertools.compositions
效果很好:

>>> for c in itertools.combinations(stuff, 7):
...     print(c)
...     
(1, 2, 3, 4, 5, 6, 7)
(1, 2, 3, 4, 5, 6, 8)
(1, 2, 3, 4, 5, 7, 8)
(1, 2, 3, 4, 6, 7, 8)
(1, 2, 3, 5, 6, 7, 8)
(1, 2, 4, 5, 6, 7, 8)
(1, 3, 4, 5, 6, 7, 8)
(2, 3, 4, 5, 6, 7, 8)

重复是由于您在循环中运行
组合

itertools。组合
工作正常:

>>> for c in itertools.combinations(stuff, 7):
...     print(c)
...     
(1, 2, 3, 4, 5, 6, 7)
(1, 2, 3, 4, 5, 6, 8)
(1, 2, 3, 4, 5, 7, 8)
(1, 2, 3, 4, 6, 7, 8)
(1, 2, 3, 5, 6, 7, 8)
(1, 2, 4, 5, 6, 7, 8)
(1, 3, 4, 5, 6, 7, 8)
(2, 3, 4, 5, 6, 7, 8)
重复是由于您在循环中运行
组合
造成的