一、概述
itertools.permutation()
如单词“Permutation”所理解的,它指的是可以对集合或字符串进行排序或排列的所有可能的组合。同样在这里itertool.permutations()方法为我们提供了迭代器可能存在的所有可能的安排,并且所有元素均根据该位置而不是根据其值或类别被假定为唯一。所有这些排列都是按字典顺序提供的。功能itertool.permutations()接受一个迭代器(字符串,元组,列表,字典)和“ r”(需要排列的长度)作为输入,并假设“ r”作为迭代器的默认长度(如果未提及),并分别返回所有可能的长度为“ r”的排列。
用法:
permutations(iterator, r)
二、实例说明
(一)对字符串进行permutations排列组合
from itertools import permutations
a = 'abc' #对字符串进行permutations排列组合
for i in permutations(a,3):
x = ''.join(i)
print (x,end=' ')
print ('\n------------------------------------')
输出结果:
说明:对字符串,元组,列表,字典不进行格式化输出的话,全是以元组形式输出。
# 不进行格式化输出,则输出元组
from itertools import permutations
a = 'abc' #对字符串进行permutations排列组合
for i in permutations(a,3):
print (i,end=' ')
print ('\n------------------------------------')
输出结果:

(二)对元组进行permutations排列组合
c = ('e','f','g') #对元组进行permutations排列组合
for j in permutations(c,2):
print (j)
print ('------------------------------')
输出结果:
(三)对列表进行permutations排列组合
b = [1,2,3] #对列表进行permutations排列组合
for j in permutations(b,3):
print (''.join('%d'%o for o in j))
print ('-----------------------------------------------------')
输出结果:

(四)对字典进行permutations排列组合
e = {'青鸟':'最美','萧风':'最帅'} #对字典进行permutations排列组合
for i in permutations(e,2):
print (''.join('%s'%s for s in i)) #字典只对键进行排列组合
print ('-----------------------------------------------------')
输出结果:

itertools.permutations()是Python中的一个函数,用于生成给定迭代器的所有可能排列。它可以应用于字符串、元组、列表和字典,返回所有可能的长度为r的排列。示例中展示了对字符串、元组、列表和字典进行排列组合的方法,注意字典只对键进行排列。输出结果通常以元组形式给出,可以通过join()函数转换为字符串形式。
447

被折叠的 条评论
为什么被折叠?



