Ruby组合方法的Python等价

2024-05-17 18:15:32 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有惯用的python方法列出列表中所有特定大小的组合?你知道吗

以下代码在ruby(here)中工作,我想知道是否有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]]

附言:我不是在寻找排列,而是特定大小的组合。你知道吗

非常感谢:)


Tags: to方法代码列表hereruby惯用combination
1条回答
网友
1楼 · 发布于 2024-05-17 18:15:32

The ^{} module has a ^{}方法,它为您执行此操作。你知道吗

itertools.combinations(a, len)

演示:

>>> a = [1, 2, 3, 4]
>>> import itertools
>>> itertools.combinations(a, 2)
<itertools.combinations object at 0x109c276d8>
>>> list(itertools.combinations(a, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
>>> list(itertools.combinations(a, 3))
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
>>> list(itertools.combinations(a, 4))
[(1, 2, 3, 4)]

相关问题 更多 >