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

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


我如何在python 3中做到这一点?

最佳答案

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长度子序列。

关于python - 具有固定长度的元组的子集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23064314/

10-11 13:01