python 实现排列组合
对于一个数组(或任何可以迭代的元素集),可以通过itertools包中的permutations和combinations轻松完成排列,组合
python3中permutations和combinations返回的是一个迭代器,可以通过list转化为一个列表,方便我们进一步处理
具体用法看下面的例子
import itertools from itertools import permutations, combinations print("Permutations of ‘bar‘") print(list(permutations(‘bar‘))) #输出结果 #Permutations of ‘bar‘ #[(‘b‘, ‘a‘, ‘r‘), (‘b‘, ‘r‘, ‘a‘), (‘a‘, ‘b‘, ‘r‘), (‘a‘, ‘r‘, ‘b‘), (‘r‘, ‘b‘, ‘a‘), (‘r‘, ‘a‘, ‘b‘)] print("Combinations of 2 letters from ‘bar‘") print(list(combinations(‘bar‘, 2))) #输出结果 #Combinations of 2 letters from ‘bar‘ #[(‘b‘, ‘a‘), (‘b‘, ‘r‘), (‘a‘, ‘r‘)]
相关推荐
Justhavefun 2020-09-25
WasteLand 2020-08-15
NVEFLY 2020-04-19
Leonwey 2020-04-11
坚持是一种品质 2020-01-04
cjcsdn 2019-11-02
Go贝壳 2015-06-14
zzhuagn 2015-07-19
AIApple 2016-09-01
Kwong 2019-07-01
wayne0 2019-06-29
琪凡睿 2016-07-18
wolaoreme 2019-06-27
zwblcz 2019-06-26
Dickzeng 2019-06-26
梵天的读书笔记 2010-06-01
Chiclaim 2019-06-25