具有固定长度的元组的子集

时间:2014-04-14 15:39:41

标签: python python-3.x

我希望有一个函数subset(("A","b","C","D"),3),它提供以下输出:

("A","b","C")
("A","b","D")
("A","C","D")
("b","C","D")

我如何在python 3中执行此操作?

1 个答案:

答案 0 :(得分:2)

为此目的明确构建了itertools.combinations函数:

>>> from itertools import combinations
>>> list(combinations(("A","b","C","D"), 3))
[('A', 'b', 'C'), ('A', 'b', 'D'), ('A', 'C', 'D'), ('b', 'C', 'D')]
>>>

来自docs

  

itertools.combinations(iterable, r)

     

从输入r返回元素的iterable长度子序列。