Combinations组合
python的itertools
库中提供了combinations
方法和permutations
可以实现排列组合
注意:方法的返回值已经不再是list,而是iterators(迭代器)
, 所以想要使用,只用将iterator 转换成list 即可
代码如下:
In [11]: test = [1,2,3,3,4]
In [12]: for i in combinations(test, 3):
...: print(i)
...:
(1, 2, 3)
(1, 2, 3)
(1, 2, 4)
(1, 3, 3)
(1, 3, 4)
(1, 3, 4)
(2, 3, 3)
(2, 3, 4)
(2, 3, 4)
(3, 3, 4)
In [17]: test = {1,1,2,2,3,3,4,4,5,5}
In [18]: for i in combinations(test, 3):
...: print(i)
...:
(1, 2, 3)
(1, 2, 4)
(1, 2, 5)
(1, 3, 4)
(1, 3, 5)
(1, 4, 5)
(2, 3, 4)
(2, 3, 5)
(2, 4, 5)
(3, 4, 5)
从上面两个例子可以发现,两者的输出是有差别的,第一个输出是有重复数据的,第二个输出是不含重复数据的,那么是怎么回事呢?
首先是官方文档对combinations
方法的介绍说的是:Elements are treated as unique based on their position, not on their value
.,意思是combinations
处理传入的可迭代参数时是根据迭代元素的位置来确定是否唯一的,和元素的值是否唯一没有关系.
那么list和dict有什么区别呢?
其实很简单:dict创建的是集合或者字典,list创建的是数组,而集合具有互异性,所以dict里面传入到combinations
方法里面的参数值只是那些不重复的元素.
permutations排列
In [22]: test = [1,2,3]
In [23]: for i in permutations(test):
...: print(i)
...:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
In [26]: test = {1,1,2,2,3,3}
In [27]: for i in permutations(test, 3):
...: print(i)
...:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
In [29]: for i in permutations(test, 2):
...: print(i)
...:
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)