itertools拼装迭代器

itertools拼装迭代器

连接多个迭代器

内置的itertools模块有一些函数可以把多个迭代器连城一个使用。

chain

chain可以把多个迭代器从头到尾连成一个迭代器。

python 复制代码
import itertools

it = itertools.chain([1, 2, 3], [4, 5, 6])
print(list(it))

>>>
[1, 2, 3, 4, 5, 6]

repeat

Repeat可以制作这样一个迭代器,它会不停地输出某个值。调用repeat时,也可以通过第二个参数指定迭代器最多能输出几次。

python 复制代码
it = itertools.repeat('hello', 3)
print(list(it))

>>>
['hello', 'hello', 'hello']

cycle

cycle可以制作这样一个迭代器,它会循环地输出某段内容之中的各项元素。

python 复制代码
it = itertools.cycle([1, 2])
result = [next(it) for _ in range(10)]
print(result)

>>>
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]

tee

tee可以让一个迭代器分裂成多个平行的迭代器,具体个数由第二个参数指定。如果这些迭代器推进的速度不一致,那么程序可能要用大量内存做缓冲,以存放进度落后的迭代器将来会用到的元素。

python 复制代码
import itertools

it1, it2, it3 = itertools.tee(['first', 'second'], 3)
print(list(it1))
print(list(it2))
print(list(it3))

>>>
['first', 'second']
['first', 'second']
['first', 'second']

zip_longest

它与Python内置的zip函数类似,但区别在于,如果源迭代器的长度不同,那么它会用fillvalue参数的值来填补提前耗尽的那些迭代器所留下的空缺。

python 复制代码
import itertools

keys = ['one', 'two', 'three', 'four', 'five']
values = [1, 2]

normal = list(zip(keys, values))
print('zip:        ', normal)

it = itertools.zip_longest(keys, values, fillvalue='nope')
longest = list(it)
print('zip_longest: ', longest)

>>>
zip:         [('one', 1), ('two', 2)]
zip_longest:  [('one', 1), ('two', 2), ('three', 'nope'), ('four', 'nope'), ('five', 'nope')]
相关推荐
MessiGo18 分钟前
Javascript 编程基础(5)面向对象 | 5.1、构造函数实例化对象
开发语言·javascript·原型模式
大霞上仙21 分钟前
nonlocal 与global关键字
开发语言·python
galaxy_strive26 分钟前
绘制饼图详细过程
开发语言·c++·qt
Mark_Aussie1 小时前
Flask-SQLAlchemy使用小结
python·flask
程序员阿龙1 小时前
【精选】计算机毕业设计Python Flask海口天气数据分析可视化系统 气象数据采集处理 天气趋势图表展示 数据可视化平台源码+论文+PPT+讲解
python·flask·课程设计·数据可视化系统·天气数据分析·海口气象数据·pandas 数据处理
ZHOU_WUYI1 小时前
Flask与Celery 项目应用(shared_task使用)
后端·python·flask
黑客老李1 小时前
JavaSec | SpringAOP 链学习分析
java·运维·服务器·开发语言·学习·apache·memcached
开开心心就好1 小时前
高效Excel合并拆分软件
开发语言·javascript·c#·ocr·排序算法·excel·最小二乘法
且慢.5891 小时前
Python_day47
python·深度学习·计算机视觉
特立独行的猫a1 小时前
Nuxt.js 中的路由配置详解
开发语言·前端·javascript·路由·nuxt·nuxtjs