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 相关文章推荐
Python记录详细调用堆栈日志的方法
May 05 Python
在Python中操作日期和时间之gmtime()方法的使用
May 22 Python
python实现决策树C4.5算法详解(在ID3基础上改进)
May 31 Python
Python进程间通信之共享内存详解
Oct 30 Python
Django中redis的使用方法(包括安装、配置、启动)
Feb 21 Python
Django Rest framework之认证的实现代码
Dec 17 Python
用Python编写一个高效的端口扫描器的方法
Dec 20 Python
对python3中, print横向输出的方法详解
Jan 28 Python
详解Django-channels 实现WebSocket实例
Aug 22 Python
python yield关键词案例测试
Oct 15 Python
在python中创建指定大小的多维数组方式
Nov 28 Python
jupyter notebook 恢复误删单元格或者历史代码的实现
Apr 17 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
用文本文件实现的动态实时发布新闻的程序
2006/10/09 PHP
图片存储与浏览一例(Linux+Apache+PHP+MySQL)
2006/10/09 PHP
php中addslashes函数与sql防注入
2014/11/17 PHP
PHP使用pcntl_fork实现多进程下载图片的方法
2014/12/16 PHP
php判断str字符串是否是xml格式数据的方法示例
2017/07/26 PHP
windows 2008r2+php5.6.28环境搭建详细过程
2019/06/18 PHP
关于js日期转化为毫秒数“节省20%的效率和和节省9个字符“问题
2012/03/01 Javascript
JavaScript高级程序设计(第3版)学习笔记7 js函数(上)
2012/10/11 Javascript
文本域光标操作的jQuery扩展分享
2014/03/10 Javascript
javaScript生成支持中文带logo的二维码(jquery.qrcode.js)
2017/01/03 Javascript
基于代数方程库Algebra.js解二元一次方程功能示例
2017/06/09 Javascript
vue实现图片滚动的示例代码(类似走马灯效果)
2018/03/03 Javascript
详解如何在你的Vue项目配置vux
2018/06/04 Javascript
快速解决vue-cli在ie9+中无效的问题
2018/09/04 Javascript
jQuery实现的别踩白块小游戏完整示例
2019/01/07 jQuery
JavaScript实现HSL拾色器
2020/05/21 Javascript
vue-cli3访问public文件夹静态资源报错的解决方式
2020/09/02 Javascript
vue操作dom元素的3种方法示例
2020/09/20 Javascript
JavaScript语法约定和程序调试原理解析
2020/11/03 Javascript
Python collections模块实例讲解
2014/04/07 Python
简单介绍Python中的filter和lambda函数的使用
2015/04/07 Python
python实现中文分词FMM算法实例
2015/07/10 Python
浅谈Python 中整型对象的存储问题
2016/05/16 Python
Python requests获取网页常用方法解析
2020/02/20 Python
Python如何输出整数
2020/06/07 Python
阿迪达斯法国官方网站:adidas法国
2018/03/20 全球购物
医疗纠纷协议书
2014/04/16 职场文书
卫生厅领导班子党的群众路线教育实践活动整改措施
2014/09/20 职场文书
光棍节联谊晚会活动策划书
2014/10/10 职场文书
婚礼新人答谢词
2015/01/04 职场文书
秋季运动会开幕词
2015/01/28 职场文书
关于长城的导游词
2015/01/30 职场文书
法学专业求职信范文
2015/03/19 职场文书
mysql中between的边界,范围说明
2021/06/08 MySQL
探讨Java中的深浅拷贝问题
2021/06/26 Java/Android
css弧边选项卡的项目实践
2023/05/07 HTML / CSS