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

 

  • 15
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

量化橙同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值