python — permutations() 函数

前言:本文讲解涉及到python中join函数,不清楚可以查看下面博客自行了解,另外了解一下和combinations()函数,product()函数三者之间的区别。

python——join和os.path.join()两个函数详细使用说明_xiaofengdada的博客-CSDN博客

python——combinations()函数_xiaofengdada的博客-CSDN博客

python——product()函数_xiaofengdada的博客-CSDN博客

一、概述

Itertools.permutation()功能属于组合发电机。用于简化组合结构(例如排列,组合和笛卡尔积)的递归生成器称为组合迭代器。

如单词“Permutation”所理解的,它指的是可以对集合或字符串进行排序或排列的所有可能的组合。同样在这里itertool.permutations()方法为我们提供了迭代器可能存在的所有可能的安排,并且所有元素均根据该位置而不是根据其值或类别被假定为唯一。所有这些排列都是按字典顺序提供的。功能itertool.permutations()接受一个迭代器和“ r”(需要排列的长度)作为输入,并假设“ r”作为迭代器的默认长度(如果未提及),并分别返回所有可能的长度为“ r”的排列。

用法:

Permutations(iterator, r)
from itertools import  permutations
#permutations(a,3)
print (permutations(a,3))
print (type(permutations(a,3)))

输出结果:


二、实例说明

(一)对字符串进行permutations排列组合

from itertools import  permutations
a = 'abc'   #对字符串进行permutations排列组合
for i in permutations(a,3):
    x = ''.join(i)
    print (x,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 ('-----------------------------------------------------')

 输出结果:

 注:字典只对键进行排列组合!

物联沃分享整理
物联沃-IOTWORD物联网 » python — permutations() 函数

发表回复