首页 > 其他 > 详细

遍历所有可能的组合或排列

时间:2019-11-06 23:21:40      阅读:222      评论:0      收藏:0      [点我收藏+]

首先来看集合的所有排列情形,itertools模块提供了permutations函数。
示例如下:

>>> items = ['a', 'b', 'c']
>>> from itertools import permutations 
>>> for p in permutations(items):
...     print(p)
...
('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
>>>

如果只想要一个长度更小的排列集合,可以提供一个可选参数r=None(默认),如下:

>>> for p in permutations(items, 2):
        print(p)
...
('a', 'b')
('a', 'c')
('b', 'a') 
('b', 'c')
('c', 'a')
('c', 'b')
>>>

接下来看组合的情况,如下示例:

>>> from itertools import combinations 
>>> for c in combinations(items, 3): 
...     print(c)
...
('a', 'b', 'c')

>>> for c in combinations(items, 2): 
...     print(c)
...
('a', 'b')
('a', 'c')
('b', 'c')
>>> for c in combinations(items, 1): 
...     print(c)
...
('a',)
('b',)
('c',)
>>>

遍历所有可能的组合或排列

原文:https://www.cnblogs.com/jeffrey-yang/p/11809187.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!