当前位置: 编程技术>python
python 排列组合之itertools
来源: 互联网 发布时间:2014-09-04
本文导语: python 2.6 引入了itertools模块,使得排列组合的实现非常简单: 代码如下:import itertools 有序排列:e.g., 4个数内选2个排列: 代码如下:>>> print list(itertools.permutations([1,2,3,4],2))[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4),...
python 2.6 引入了itertools模块,使得排列组合的实现非常简单:
import itertools
有序排列:e.g., 4个数内选2个排列:
>>> print list(itertools.permutations([1,2,3,4],2))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
无序组合:e.g.,4个数内选2个:
>>> print list(itertools.combinations([1,2,3,4],2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
代码如下:
import itertools
有序排列:e.g., 4个数内选2个排列:
代码如下:
>>> print list(itertools.permutations([1,2,3,4],2))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
无序组合:e.g.,4个数内选2个:
代码如下:
>>> print list(itertools.combinations([1,2,3,4],2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]