Python 中迭代器与生成器实例详解
作者:lqh 时间:2023-02-27 14:47:41
Python 中迭代器与生成器实例详解
本文通过针对不同应用场景及其解决方案的方式,总结了Python中迭代器与生成器的一些相关知识,具体如下:
1.手动遍历迭代器
应用场景:想遍历一个可迭代对象中的所有元素,但是不想用for循环
解决方案:使用next()函数,并捕获StopIteration异常
def manual_iter():
with open('/etc/passwd') as f:
try:
while True:
line=next(f)
if line is None:
break
print(line,end='')
except StopIteration:
pass
#test case
items=[1,2,3]
it=iter(items)
next(it)
next(it)
next(it)
2.代理迭代
应用场景:想直接在一个包含有列表、元组或其他可迭代对象的容器对象上执行迭代操作
解决方案:定义一个iter()方法,将迭代操作代理到容器内部的对象上
示例:
class Node:
def __init__(self,value):
self._value=value
self._children=[]
def __repr__(self):
return 'Node({!r})'.fromat(self._value)
def add_child(self,node):
self._children.append(node)
def __iter__(self):
#将迭代请求传递给内部的_children属性
return iter(self._children)
#test case
if __name='__main__':
root=Node(0)
child1=Node(1)
child2=Nide(2)
root.add_child(child1)
root.add_child(child2)
for ch in root:
print(ch)
3.反向迭代
应用场景:想要反向迭代一个序列
解决方案:使用内置的reversed()函数或者在自定义类上实现reversed()
示例1
a=[1,2,3,4]
for x in reversed(a):
print(x) #4 3 2 1
f=open('somefile')
for line in reversed(list(f)):
print(line,end='')
#test case
for rr in reversed(Countdown(30)):
print(rr)
for rr in Countdown(30):
print(rr)
示例2
class Countdown:
def __init__(self,start):
self.start=start
#常规迭代
def __iter__(self):
n=self.start
while n > 0:
yield n
n -= 1
#反向迭代
def __reversed__(self):
n=1
while n <= self.start:
yield n
n +=1
4.有选择的迭代
应用场景:想遍历一个可迭代对象,但是对它开始的某些元素并不感兴趣,想跳过
解决方案:使用itertools.dropwhile()
示例1
with open('/etc/passwd') as f:
for line in f:
print(line,end='')
示例2
from itertools import dropwhile
with open('/etc/passwd') as f:
for line in dropwhile(lambda line:line.startwith('#'),f):
print(line,end='')
5.同时迭代多个序列
应用场景:想同时迭代多个序列每次分别从一个序列中取一个元素
解决方案:使用zip()函数
6.不同集合上元素的迭代
应用场景:想在多个对象执行相同的操作,但是这些对象在不同的容器中
解决方案:使用itertool.chain()函数
7.展开嵌套的序列
应用场景:想将一个多层嵌套的序列展开成一个单层列表
解决方案:使用包含yield from语句的递归生成器
示例
from collections import Iterable
def flatten(items,ignore_types=(str,bytes)):
for x in items:
if isinstance(x,Iterable) and not isinstance(x,ignore_types):
yield from flatten(x)
else:
yield x
#test case
items=[1,2,[3,4,[5,6],7],8]
for x in flatten(items):
print(x)
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
来源:http://blog.csdn.net/arthur_02_13/article/details/67634292
标签:Python,迭代器,生成器
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅谈Django REST Framework限速
2022-04-09 20:54:46
![](https://img.aspxhome.com/file/2023/1/131311_0s.jpg)
python通过装饰器检查函数参数数据类型的方法
2022-07-22 14:11:08
Python datatime库语法使用详解
2022-01-30 03:16:17
![](https://img.aspxhome.com/file/2023/6/83846_0s.png)
PPOCRLabel标注的txt格式如何转换成labelme能修改的json格式
2021-08-31 06:01:45
![](https://img.aspxhome.com/file/2023/7/107087_0s.jpg)
PHP取整函数:ceil,floor,round,intval的区别详细解析
2023-11-17 18:30:33
python2.7 json 转换日期的处理的示例
2021-02-10 12:39:50
Java中使用正则表达式的一个简单例子及常用正则分享
2023-05-06 09:03:16
python实现根据图标提取分类应用程序实例
2022-07-23 16:22:39
asp如何建立和删除文件夹?
2009-11-26 20:34:00
Go语言命令行操作命令详细介绍
2023-07-22 16:15:40
![](https://img.aspxhome.com/file/2023/4/86294_0s.png)
go语言环境搭建简述
2024-05-22 10:12:57
HTML5本地存储初探(二)
2010-03-07 15:47:00
![](https://img.aspxhome.com/file/UploadPic/20103/7/20100131-rmki9pjq85xy9nbt436gkdfb7i-94s.png)
Python生成一个迭代器的实操方法
2022-05-08 09:34:32
![](https://img.aspxhome.com/file/2023/0/114560_0s.jpg)
Python中if elif else及缩进的使用简述
2021-06-18 18:29:36
python实现点击按钮修改数据的方法
2023-08-18 20:46:08
Python3实现的字典、列表和json对象互转功能示例
2022-11-10 11:04:51
SQL Server常见问题及解决方法分享
2024-01-15 01:45:30
![](https://img.aspxhome.com/file/2023/4/108534_0s.png)
MYSQL的select 学习笔记
2024-01-21 17:48:50
SQL Server误区30日谈 第10天 数据库镜像在故障发生后 马上就能发现
2024-01-13 02:40:08
Python3中map()、reduce()、filter()的用法详解
2024-01-03 01:27:23