【Python】permutations()函数

您所在的位置:网站首页 python组合数怎么打 【Python】permutations()函数

【Python】permutations()函数

2024-06-12 13:12| 来源: 网络整理| 查看: 265

一、概述

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 ('-----------------------------------------------------')

 输出结果:

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


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3