One - One Code All

Blog Content

python全排列combinations和permutations函数

Python   2016-08-12 21:05:02

combinations方法重点在组合,permutations方法重在排列。


combinations和permutations返回的是对象地址,原因是在python3里面,返回值已经不再是list,而是iterators(迭代器), 

所以想要使用,只用将iterator 转换成list 即可, 还有其他一些函数返回的也是一个对象,需要list转换,比如 list(map())等 。


>>> from itertools import combinations

>>> test_data = {'a', 'a', 'a', 'b'}

>>> for i in combinations(test_data, 2):

...     print(i)

...

('b', 'a')

>>> test_data1 = ['a', 'a', 'a', 'b']

>>> for i in combinations(test_data1, 2):

...     print(i)

...

('a', 'a')

('a', 'a')

('a', 'b')

('a', 'a')

('a', 'b')

('a', 'b')


使用大括号{}创建的是集合或者字典,使用中括号[]创建的是数组,而集合具有互异性! 

所以不管在{}里面写了多少个a,其实传入到combinations方法里面的参数值都只是:'a','b'。



上一篇:numpy之random库简单的随机排列.shuffle(x)、.permutation(x)
下一篇:MongoDB初步使用

The minute you think of giving up, think of the reason why you held on so long.