0

在 Python 中,有没有比嵌套 for 循环或列表推导更好的方法来从 k 元素集中获取 n 个元素的组合集?

例如,从集合 [1,2,3,4,5,6] 我想得到 [(1,2),(1,3),(1,4),(1,5),( 1,6),(2,3),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6),(4, 5),(4,6),(5,6)]。有没有比制作它更好的方法

nums=[1,2,3,4,5,6]
doubles=[]
for a in nums:
    for b in nums[a+1:]
        doubles.append((a,b))

? 如果我们最终得到的列表元素是集合、元组或列表,那也没关系;我只是觉得应该有一个更简单的方法来做到这一点。

4

3 回答 3

4

您可以使用itertools.combinations

>>> from itertools import combinations
>>> nums = [1,2,3,4,5,6]
>>> list(combinations(nums, 2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
于 2013-06-11T20:24:04.717 回答
3

itertools模块有很多非常强大的工具,可以在这种情况下使用。在这种情况下,您需要itertools.combinations. 您可能会觉得有用的其他一些是itertools.combinations_with_replacementitertools.permutations

例子:

>>> import itertools
>>> list(itertools.combinations(range(1,7),2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]
>>> list(itertools.combinations_with_replacement(range(1,7),2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 3), (3, 4), (3, 5), (3, 6), (4, 4), (4, 5), (4, 6), (5, 5), (5, 6), (6, 6)]
>>> list(itertools.permutations(range(1,7),2))
[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5)]
于 2013-06-11T20:23:53.667 回答
1

您可以使用 itertools 模块

import itertools
alphabet = ['1','2','3','4','5','6']
combos = list(itertools.combinations(alphabet, 2))
print combos
于 2013-06-11T20:28:11.500 回答