Python 迭代器工具包【推荐】


Posted in Python onMay 06, 2016

原文:https://git.io/pytips

0x01 介绍了迭代器的概念,即定义了 __iter__() __next__() 方法的对象,或者通过 yield 简化定义的“可迭代对象”,而在一些函数式编程语言(见 0x02 Python 中的函数式编程)中,类似的迭代器常被用于产生特定格式的列表(或序列),这时的迭代器更像是一种数据结构而非函数(当然在一些函数式编程语言中,这两者并无本质差异)。Python 借鉴了 APL, Haskell, and SML 中的某些迭代器的构造方法,并在 itertools 中实现(该模块是通过 C 实现,源代码:/Modules/itertoolsmodule.c)。

  itertools 模块提供了如下三类迭代器构建工具:

无限迭代

整合两序列迭代

组合生成器

  1. 无限迭代

所谓无限(infinite)是指如果你通过 for...in... 的语法对其进行迭代,将陷入无限循环,包括:

count(start, [step])

cycle(p)


repeat(elem [,n])

从名字大概可以猜出它们的用法,既然说是无限迭代,我们自然不会想要将其所有元素依次迭代取出,而通常是结合 map/zip 等方法,将其作为一个取之不尽的数据仓库,与有限长度的可迭代对象进行组合操作:

from itertools import cycle, count, repeat
print(count.__doc__)
count(start=0, step=1) --> count object

Return a count object whose .__next__() method returns consecutive values.

Equivalent to:

def count(firstval=0, step=1):

x = firstval

while 1:

yield x

x += step

counter = count()

print(next(counter))
  print(next(counter))

print(list(map(lambda x, y: x+y, range(10), counter)))

odd_counter = map(lambda x: 'Odd#{}'.format(x), count(1, 2))
  print(next(odd_counter))

print(next(odd_counter))


0


1


[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]


Odd#1


Odd#3


print(cycle.__doc__)


cycle(iterable) --> cycle object


Return elements from the iterable until it is exhausted.


Then repeat the sequence indefinitely.


cyc = cycle(range(5))


print(list(zip(range(6), cyc)))


print(next(cyc))


print(next(cyc))


[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 0)]


1


2


print(repeat.__doc__)


repeat(object [,times]) -> create an iterator which returns the object


for the specified number of times. If not specified, returns the object


endlessly.


print(list(repeat('Py', 3)))


rep = repeat('p')


print(list(zip(rep, 'y'*3)))


['Py', 'Py', 'Py']


[('p', 'y'), ('p', 'y'), ('p', 'y')]

2. 整合两序列迭代

所谓整合两序列,是指以两个有限序列为输入,将其整合操作之后返回为一个迭代器,最为常见的 zip 函数就属于这一类别,只不过 zip 是内置函数。这一类别完整的方法包括:

 

 accumulate()

chain()/chain.from_iterable()


compress()


dropwhile()/filterfalse()/takewhile()


groupby()


islice()


starmap()


tee()


zip_longest()

这里就不对所有的方法一一举例说明了,如果想要知道某个方法的用法,基本通过 print(method.__doc__) 就可以了解,毕竟 itertools 模块只是提供了一种快捷方式,并没有隐含什么深奥的算法。这里只对下面几个我觉得比较有趣的方法进行举例说明。

from itertools import cycle, compress, islice, takewhile, count

# 这三个方法(如果使用恰当)可以限定无限迭代


# print(compress.__doc__)


print(list(compress(cycle('PY'), [1, 0, 1, 0])))


# 像操作列表 l[start:stop:step] 一样操作其它序列


# print(islice.__doc__)


print(list(islice(cycle('PY'), 0, 2)))


# 限制版的 filter


# print(takewhile.__doc__)


print(list(takewhile(lambda x: x < 5, count())))


['P', 'P']


['P', 'Y']


[0, 1, 2, 3, 4]


from itertools import groupby


from operator import itemgetter


print(groupby.__doc__)


for k, g in groupby('AABBC'):


print(k, list(g))


db = [dict(name='python', script=True),


dict(name='c', script=False),


dict(name='c++', script=False),


dict(name='ruby', script=True)]


keyfunc = itemgetter('script')


db2 = sorted(db, key=keyfunc) # sorted by `script'


for isScript, langs in groupby(db2, keyfunc):


print(', '.join(map(itemgetter('name'), langs)))


groupby(iterable[, keyfunc]) -> create an iterator which returns


(key, sub-iterator) grouped by each value of key(value).


A ['A', 'A']


B ['B', 'B']


C ['C']


c, c++


python, ruby


from itertools import zip_longest


# 内置函数 zip 以较短序列为基准进行合并,


# zip_longest 则以最长序列为基准,并提供补足参数 fillvalue


# Python 2.7 中名为 izip_longest


print(list(zip_longest('ABCD', '123', fillvalue=0)))


[('A', '1'), ('B', '2'), ('C', '3'), ('D', 0)]

3. 组合生成器

关于生成器的排列组合: 

product(*iterables, repeat=1):两输入序列的笛卡尔乘积

permutations(iterable, r=None):对输入序列的完全排列组合


combinations(iterable, r):有序版的排列组合


combinations_with_replacement(iterable, r):有序版的笛卡尔乘积


from itertools import product, permutations, combinations, combinations_with_replacement


print(list(product(range(2), range(2))))


print(list(product('AB', repeat=2)))


[(0, 0), (0, 1), (1, 0), (1, 1)]


[('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]


print(list(combinations_with_replacement('AB', 2)))


[('A', 'A'), ('A', 'B'), ('B', 'B')]


# 赛马问题:4匹马前2名的排列组合(A^4_2)


print(list(permutations('ABCDE', 2)))


[('A', 'B'), ('A', 'C'), ('A', 'D'), 
 ('A', 'E'), ('B', 'A'), ('B', 'C'), 
 ('B', 'D'), ('B', 'E'), ('C', 'A'), 
 ('C', 'B'), ('C', 'D'), ('C', 'E'), 
 ('D', 'A'), ('D', 'B'), ('D', 'C'), 
 ('D', 'E'), ('E', 'A'), ('E', 'B'), ('E', 'C'), ('E', 'D')]


# 彩球问题:4种颜色的球任意抽出2个的颜色组合(C^4_2)


print(list(combinations('ABCD', 2)))


[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
Python 相关文章推荐
linux系统使用python获取内存使用信息脚本分享
Jan 15 Python
Python中操作mysql的pymysql模块详解
Sep 13 Python
Python图形绘制操作之正弦曲线实现方法分析
Dec 25 Python
全面分析Python的优点和缺点
Feb 07 Python
Python中的元组介绍
Jan 28 Python
Python定义函数功能与用法实例详解
Apr 08 Python
在PyCharm中控制台输出日志分层级分颜色显示的方法
Jul 11 Python
基于numpy中的expand_dims函数用法
Dec 18 Python
python中matplotlib实现随鼠标滑动自动标注代码
Apr 23 Python
全面介绍python中很常用的单元测试框架unitest
Dec 14 Python
Python创建简单的神经网络实例讲解
Jan 04 Python
使用pipenv管理python虚拟环境的全过程
Sep 25 Python
Python中内建函数的简单用法说明
May 05 #Python
Python使用Paramiko模块编写脚本进行远程服务器操作
May 05 #Python
Python环境下搭建属于自己的pip源的教程
May 05 #Python
使用Python判断质数(素数)的简单方法讲解
May 05 #Python
Python编程中归并排序算法的实现步骤详解
May 04 #Python
Python手机号码归属地查询代码
May 04 #Python
图文讲解选择排序算法的原理及在Python中的实现
May 04 #Python
You might like
Terran建筑一览
2020/03/14 星际争霸
PHP实现事件机制实例分析
2015/06/26 PHP
Laravel配合jwt使用的方法实例
2020/10/25 PHP
静态的动态续篇之来点XML
2006/12/23 Javascript
ExtJS Window 最小化的一种方法
2009/11/18 Javascript
基于JQuery的数字改变的动画效果--可用来做计数器
2010/08/11 Javascript
JavaSript中变量的作用域闭包的深入理解
2014/05/12 Javascript
JavaScript面对国际化编程时的一些建议
2015/06/24 Javascript
基于jQuery实现响应式圆形图片轮播特效
2015/11/25 Javascript
Jquery左右滑动插件之实现超级炫酷动画效果附源码下载
2015/12/02 Javascript
JS实现用户注册时获取短信验证码和倒计时功能
2016/10/27 Javascript
JS闭包与延迟求值用法示例
2016/12/22 Javascript
Reactjs实现通用分页组件的实例代码
2017/01/19 Javascript
微信小程序中时间戳和日期的相互转换问题
2018/07/09 Javascript
vue slot与传参实例代码讲解
2019/04/28 Javascript
vue-cli配置flexible过程详解
2019/07/04 Javascript
Vue基本指令实例图文讲解
2021/02/25 Vue.js
[51:26]VP vs VG 2018国际邀请赛小组赛BO2 第二场 8.19
2018/08/21 DOTA
简单介绍Python中的decode()方法的使用
2015/05/18 Python
python实现计算倒数的方法
2015/07/11 Python
Python读写Json涉及到中文的处理方法
2016/09/12 Python
Django中针对基于类的视图添加csrf_exempt实例代码
2018/02/11 Python
Python装饰器的执行过程实例分析
2018/06/04 Python
数据清洗--DataFrame中的空值处理方法
2018/07/03 Python
详解Python网络框架Django和Scrapy安装指南
2019/04/01 Python
tensorflow实现测试时读取任意指定的check point的网络参数
2020/01/21 Python
解决python执行较大excel文件openpyxl慢问题
2020/05/15 Python
如何利用python生成MD5并去重
2020/12/07 Python
英国在线购买轮胎、预订汽车、汽车维修和装配网站:Protyre
2020/04/12 全球购物
村官工作鉴定评语
2014/01/27 职场文书
物流业务员岗位职责
2014/02/08 职场文书
党员干部民主生活会议批评与自我批评材料
2014/09/20 职场文书
2014年银行个人工作总结
2014/12/05 职场文书
团员个人总结
2015/02/26 职场文书
新手必备Python开发环境搭建教程
2021/05/28 Python
教你使用一行Python代码玩遍童年的小游戏
2021/08/23 Python