Files
Python_CookBook_repo/4.迭代器与生成器/9.迭代所有的排列组合.py
2025-09-10 16:12:45 +08:00

24 lines
921 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from itertools import permutations, combinations
if __name__ == '__main__':
# 有时候我们想对可迭代对象中的元素进行排列组合这个时候我们就不得不靠for循环写出很不python的代码
# itertools库帮助我们解决了这个困扰
items= ['a', 'b', 'c', 'd', 'e']
# permutations会列出所有的排列如果指定排列长度那就会输出该长度下所有的排列
for p in permutations(items):
print(p)
for p in permutations(items, 3):
print(p)
# 如果想要得到特定长度的组合那就可以使用combination函数
for c in combinations(items, 3):
print(c)
# 上面这种组合是不放回的组合如果想产生放回元素的组合可以使用combinations_with_replacement函数
from itertools import combinations_with_replacement as cwr
for c in cwr(items, 3):
print(c)