当面对看起来很复杂的迭代问题时,可以先去看下itertools模块中是否已经有解决方案。本文举例出几个列表排列组合的迭代方法。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2024/8/19 下午9:37
# @Author : s
from itertools import permutations, combinations, combinations_with_replacement
# permutations:对一个元素集合中所有元素排列出所有可能情况, 默认是集合中所有元素,可传参
# combinations:对一个元素集合中所有组合情况,需要传参,且去重
# combinations_with_replacement:对一个元素集合中所有组合情况,需要传参,不去重
items = ['a', 'b', 'c']
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')
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',)
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')
for c in combinations_with_replacement(items, 2):
print(c)
# ('a', 'a')
# ('a', 'b')
# ('a', 'c')
# ('b', 'b')
# ('b', 'c')
# ('c', 'c')