Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby组合方法的Python等价物_Python_Arrays_Ruby - Fatal编程技术网

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,

是否有一种惯用的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,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)]

非常感谢。。知道了。如我所料,我会接受你的回答。非常感谢。。知道了。正如我所料,我会接受你的回答。