Ruby组合方法的Python等价物
是否有一种惯用的python方法从列表中列出所有特定大小的组合 以下代码在ruby()中工作,我想知道是否有与此类似的python:Ruby组合方法的Python等价物,python,arrays,ruby,Python,Arrays,Ruby,是否有一种惯用的python方法从列表中列出所有特定大小的组合 以下代码在ruby()中工作,我想知道是否有与此类似的python: a = [1, 2, 3, 4] a.combination(1).to_a #=> [[1],[2],[3],[4]] a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,
a = [1, 2, 3, 4]
a.combination(1).to_a #=> [[1],[2],[3],[4]]
a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
PS:我不是在寻找排列,而是特定大小的组合
非常感谢:)为您提供此功能的方法
itertools.combinations(a, len)
演示:
>a=[1,2,3,4]
>>>进口itertools
>>>itertools.组合(a,2)
>>>列表(itertools.组合(a,2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
>>>列表(itertools.组合(a,3))
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
>>>列表(itertools.组合(a,4))
[(1, 2, 3, 4)]
为您执行此操作的方法
itertools.combinations(a, len)
演示:
>a=[1,2,3,4]
>>>进口itertools
>>>itertools.组合(a,2)
>>>列表(itertools.组合(a,2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
>>>列表(itertools.组合(a,3))
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
>>>列表(itertools.组合(a,4))
[(1, 2, 3, 4)]
非常感谢。。知道了。如我所料,我会接受你的回答。非常感谢。。知道了。正如我所料,我会接受你的回答。