python itertools模块

在数据处理中还比较常见,整理了一下。内容主要来自 python 官方文档,更多详细,请参考这里

这是一个python内建的模块,主要用于实现迭代。灵感来源于APL、Haskell and SML等语言。

特点:以纯python的方式来实现,速度较快。

无限迭代函数,主要有三个

iteratorargumentsresultsexample
count()start, [step]start, start+step, start+2*step, …count(10) --> 10 11 12 13 14 …
cycle()pp0, p1, … plast, p0, p1, …cycle(‘ABCD’) --> A B C D A B C D …
repeat()elem [,n]elem, elem, elem, … endlessly or up to n timesrepeat(10, 3) --> 10 10 10

非无限迭代

函数较多。比如accumulate() 返回累加的值的迭代,

组合迭代

比较有趣,主要有四个

IteratorArgumentsResults
product()p, q, … [repeat=1]cartesian product, equivalent to a nested for-loop类似于做笛卡尔积
permutations()p[, r]r-length tuples, all possible orderings, no repeated elements r个元素的全排列
combinations()p, rr-length tuples, in sorted order, no repeated elements r个元素的组合排列
combinations_with_replacement()p, rr-length tuples, in sorted order, with repeated elements 允许放回的组合排列
product(‘ABCD’, repeat=2)AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permutations(‘ABCD’, 2)AB AC AD BA BC BD CA CB CD DA DB DC
combinations(‘ABCD’, 2)AB AC AD BC BD CD
combinations_with_replacement(‘ABCD’, 2)AA AB AC AD BB BC BD CC CD DD

应用示例

求质数序列中1,3,5,7,9,11,13,15三个数之和为35的三个数;

def get_three_data(data_list,amount):
    for data in list(itertools.combinations(data_list, 3)):
        if sum(data) == amount:
            print(data)
#(7, 13, 15)
#(9, 11, 15)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值