用python实现排列组合

来源:互联网 发布:知所然又知其所以然 编辑:程序博客网 时间:2024/05/17 18:40

比如我们要实现1,2,3的排列组合,我们可以很容易写出来,如下表:

  1个元素2个元素3个元素不考虑顺序1231,2,312,13,23123考虑顺序1231,2,3,12,21,13,31,23,32123,132,213,231,312,321用代码实现,首先是不考虑顺序的:

#选取2个对象
import itertoolsprint list(itertools.combinations([1,2,3,4],3))[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
#选取3个对象

import itertools
print list(itertools.combinations([1,2,3,4],2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

考虑顺序

import itertoolsprint list(itertools.permutations([1,2,3,4],2))  #第二个参数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)] 

总结:主要实例分析了itertools库里combinations函数与permutations函数的区别

combinations:不考虑顺序的排列组合

permutations:考虑顺序的排列组合

原创粉丝点击