itertools --迭代所有可能的组合或排列

问题:想对一系列元素所有可能的组合或排列进行迭代

1、itertools.permutations() 它接受一个元素集合,将其中的元素排列为所有可能的情况,并以元组序列的形式返回

import itertools

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

for p in itertools.permutations(items, 2):  # 可以提供一个可选的长度参数
    print(p)
    
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'c')
('c', 'a')
('c', 'b')

2、itertools.combinations() 可产生输入序列中所有元素的全部组合形式
对于combinations()来说,元素之间的实际顺序是不作考虑的,组合(‘a’, ‘b’)和(‘b’, ‘a’)被认为是相同的组合形式。

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

for p in itertools.combinations(items, 2):
    print(p)
    
('a', 'b')
('a', 'c')
('b', 'c')

3、当产生组合时,已经选择过的元素将从可能的候选元素中移除掉。itertools.combinations_with_replacement()函数将解放这一限制,允许相同的元素多次选择

for c in itertools.combinations_with_replacement(items, 3):
    print(c)
    
('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'c')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'c')
('c', 'c', 'c')
总结:

当面对很复杂的迭代问题时,应该总是先去看看itertools模块,如果问题比较常见,那么很可能已经有现成的解决方案了

    原文作者:cook__
    原文地址: https://www.jianshu.com/p/30a232622174
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞