python itertools包内置无限迭代器
作者:alex1801 时间:2023-11-16 18:58:59
前言:
Python的内建模块itertools
提供了非常有用的用于操作迭代对象的函数,itertools提供的几个“无限”迭代器
1、count()创建自然数序列
import itertools
n = 0
natuals = itertools.count(1)
for m in natuals:
print(m)
因为count(n)
会创建一个无限的迭代器,起始数字为n,迭代至无穷大。所以上述代码会打印出自然数序列,根本停不下来,只能按Ctrl+C退出。
运行结果:
0 1 2 3 4 5 6 7 ...
2、cycle()创建序列循环
cycle()
会把传入的一个序列无限重复下去。
示例1、循环列表中的内容:
natuals = itertools.cycle([1, 2, 3])
for m in natuals:
print(m)
运行结果:
1 2 3 1 2 3 1 2 3 ...
示例2、字符串中字符循环:
import itertools
cs = itertools.cycle('ABC') # 注意字符串也是序列的一种
for c in cs:
print(c)
运行结果:
A B C A B C A B C ...
3、repeat()把一个元素有限次重复
repeat()
负责把一个元素无限重复下去(默认行为),不过如果提供第二个参数就可以限定重复次数。
ns = itertools.repeat('A', 3)
for n in ns:
print(n)
运行结果:
A A A ...
4、takewhile()根据条件判断来截取出一个有限的序列
无限序列只有在for迭代时才会无限地迭代下去,如果只是创建了一个迭代对象,它不会事先把无限个元素生成出来,事实上也不可能在内存中创建无限多个元素。无限序列虽然可以无限迭代下去,但是通常我们会通过takewhile()等函数根据条件判断来截取出一个有限的序列。
import itertools
natuals = itertools.count(1)
ns = itertools.takewhile(lambda x: x <= 10, natuals)
print(list(ns))
运行结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
迭代器测试:
对于有限数据的迭代器,每调用一次,迭代器内数据弹出。
import itertools
natuals = itertools.count(1)
ns = itertools.takewhile(lambda x: x <= 3, natuals)
for n in ns:
print(n)
print(list(ns))
运行结果:
1 2 3 []
5、chain()迭代对象串联
chain()可以把一组迭代对象串联起来,形成一个更大的迭代器。
for c in itertools.chain('ABC', 'XYZ'):
print(c)
运行结果:
'A' 'B' 'C' 'X' 'Y' 'Z'
6、groupby()迭代器元素分组
groupby()
把迭代器中相邻的重复元素挑出来放在一起,更多的用于字符串。
for key, group in itertools.groupby('AAABBBCCAAA'):
print(key, list(group))
运行结果:
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']
实际上挑选规则是通过函数完成的,只要作用于函数的两个元素返回的值相等,这两个元素就被认为是在一组的,而函数返回值作为组的key。如果我们要忽略大小写分组,就可以让元素'A'和'a'都返回相同的key。
for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
print(key, list(group))
运行结果:
A ['A', 'a', 'a']
B ['B', 'B', 'b']
C ['c', 'C']
A ['A', 'A', 'a']
来源:https://blog.csdn.net/weixin_34910922/article/details/122831611
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python正则表达式匹配ip地址实例
彻底删除SQL Server注册表的方法
python排序的方法实例总结
php判断输入不超过mysql的varchar字段的长度范围
python遗传算法之单/多目标规划问题
![](https://img.aspxhome.com/file/2023/8/76878_0s.png)
深入理解Python 多线程
![](https://img.aspxhome.com/file/2023/1/110221_0s.png)
VsCode插件整理(小结)
![](https://img.aspxhome.com/file/2023/6/132236_0s.png)
php5.2 Json不能正确处理中文、GB编码的解决方法
JavaScript 图片变换效果(ie only)
![](https://img.aspxhome.com/file/UploadPic/20101/20/2010120125735780s.gif)
Python 虚拟环境工作原理解析
基于Python正确读取资源文件
![](https://img.aspxhome.com/file/2023/2/130982_0s.png)
Python数据可视化库seaborn的使用总结
![](https://img.aspxhome.com/file/2023/3/82633_0s.png)
创建Vue项目以及引入Iview的方法示例
js 代码优化点滴记录
mysq启动失败问题及场景分析
![](https://img.aspxhome.com/file/2023/3/128433_0s.jpg)
JavaScript 设计模式 富有表现力的Javascript(一)
基于js粘贴事件paste简单解析以及遇到的坑
Python pandas中apply函数简介以及用法详解
![](https://img.aspxhome.com/file/2023/4/121734_0s.png)