python 遍历所有可能的组合和排列

2022-05-16  本文已影响0人  孙广宁
4.9 如果我们相对一系列元素所有可能的组合或排列进行遍历
>>> 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')
>>>
>>> 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')
>>>
>>> from itertools import combinations_with_replacement
>>> for c in 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')
>>>
上一篇下一篇

猜你喜欢

热点阅读