python 排列组合函数 | 您所在的位置:网站首页 › 任意数字组合公式怎么设置 › python 排列组合函数 |
在使用python进行运算的时候,经常会遇到对list或者dict中任意两个元素,或者任意多个元素之间进行运算,这就涉及到了排列组合的知识。比较幸运的是在python的itertools包中提供了和排列组合相关的函数 上代码: from itertools import combinations,permutations a=[1,2,3,4] b=[2,4,6,8] c = list(combinations(a,2)) d = list(permutations(b,3)) print(c) print(d) 运算结果: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] [(2, 4, 6), (2, 4, 8), (2, 6, 4), (2, 6, 8), (2, 8, 4), (2, 8, 6), (4, 2, 6), (4, 2, 8), (4, 6, 2), (4, 6, 8), (4, 8, 2), (4, 8, 6), (6, 2, 4), (6, 2, 8), (6, 4, 2), (6, 4, 8), (6, 8, 2), (6, 8, 4), (8, 2, 4), (8, 2, 6), (8, 4, 2), (8, 4, 6), (8, 6, 2), (8, 6, 4)]很好用吧,下面附带一个例子供大家学习 import math import itertools from itertools import combinations print(unique) ## [ 1 2 3 4 5 56 78 23] i=0 for combination in combinations(unique, 2): print(combination) i += 1 print(i) ## 输出为28 print(math.factorial( len(unique) )/(2 * math.factorial( len(unique)-2 ))) ## 输出为28 ## 笛卡尔积 d = 0 uniques = [unique, unique] for combination in itertools.product(*uniques): print(combination) d += 1 print(d) ## 输出为64
|
CopyRight 2018-2019 实验室设备网 版权所有 |