2025-09-10:仓库迁移
This commit is contained in:
23
4.迭代器与生成器/9.迭代所有的排列组合.py
Normal file
23
4.迭代器与生成器/9.迭代所有的排列组合.py
Normal file
@@ -0,0 +1,23 @@
|
||||
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)
|
||||
|
Reference in New Issue
Block a user