程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2024-11(2)

python之itertools实现排列组合

发布于2020-03-13 12:21     阅读(1224)     评论(0)     点赞(19)     收藏(3)


itertools 是python的迭代器模块,里面有很多函数可以用来高效生成迭代器,《python之itertools模块》这篇文章写得挺详细的,有兴趣的可以看看。
这里只介绍一下排列组合的几个函数。
product 笛卡尔积 (有放回抽样排列)
permutations 排列 (不放回抽样排列)
combinations 组合,没有重复 (不放回抽样组合)
combinations_with_replacement 组合,有重复 (有放回抽样组合)

一、product

product函数中的repeat可以理解为参数重复次数,默认repeat=1;product可以处理一个到多个对象,这里以2个举例

import itertools

b = [1,2,3]
k = [4,5]
c = itertools.product(b,k,repeat=1)
for i in c:
    print(i)
print('=='*20)
z = itertools.product(b,k,repeat=2)
for i in z:
    print(i)

在这里插入图片描述

二、permutations

permutations函数就是用来求数学课上教的排列

b = [1,2,3]
d = itertools.permutations(b,3)
for i in d:
    print(i)

在这里插入图片描述

三、combinations

组合

b = [1,2,3]
e = itertools.combinations(b,2)
for i in e:
    print(i)

在这里插入图片描述

四、combinations_with_replacement

有放回抽样组合

b = [1,2,3]
f = itertools.combinations_with_replacement(b,2)
for i in f:
    print(i)

在这里插入图片描述



所属网站分类: 技术文章 > 博客

作者:恋爱后女盆友的变化

链接:https://www.pythonheidong.com/blog/article/256261/c75c320406f5390b9370/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

19 0
收藏该文
已收藏

评论内容:(最多支持255个字符)