查找任何计数列表的所有组合

时间:2014-08-02 19:05:20

标签: python

我正在寻找一种方法来生成给定列表中具有给定计数输出的所有项目组合。输入将是列表和每个返回组合中的项目数。例如:

list = [a, b, c, d]
number of items in output: 2

返回:

[(a, b), (a, c), (a, d), (b, c), (b, d), (c, d)]

输出中具有项目数的相同列表:3

返回:

[(a, b, c), (a, b, d), (a, c, d), (b, c, d)]

请注意(a,b)==(b,a)等。

谢谢!

2 个答案:

答案 0 :(得分:1)

您想要itertools.combinations

>>> list(itertools.combinations(['a', 'b', 'c', 'd'], 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> list(itertools.combinations(['a', 'b', 'c', 'd'], 3))
[('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'c', 'd'), ('b', 'c', 'd')]

答案 1 :(得分:0)

itertools具有permutations功能以及combinations