如何在python中获取长度为n的所有组合 [英] How to get all combinations of length n in python
本文介绍了如何在python中获取长度为n的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有任何方法可以从数字列表中获取长度为 n
的所有组合。
I was wondering if there is any way of getting all combinations of length n
from a list of numbers.
例如,如果我的列表是 [1、2、3、4]
,而我想输出(如果我选择n = 3)
For example, if my list is [1, 2, 3, 4]
, and I want to output (if I chose n = 3)
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]
[2,1,3]之类的其他排列对我没有用。
the other permutations like [2,1,3] are of no use to me.
推荐答案
itertools 可以做到这一点
import itertools
for comb in itertools.combinations([1, 2, 3, 4], 3):
print comb
输出
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
这篇关于如何在python中获取长度为n的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文