24 lines
921 B
Python
24 lines
921 B
Python
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)
|
||
|