随笔 - 139  文章 - 1  评论 - 0  阅读 - 47214

Python自动化开发-迭代器

Python自动化开发-迭代器

迭代器基础概念

迭代器:迭代器即迭代的工具,那什么是迭代呢?迭代是一个重复的过程,每次重复即一次迭代,并且每次迭代的结果都是下一次迭代的初始值。

可迭代对象:可迭代对象指的是内置有__iter__方法的对象,即obj.__iter__。

迭代器对象:可迭代对象执行obj.__iter__()得到的结果就是迭代器对象,而迭代器对象指的是即内置有__iter__又内置有__next__方法的对象。

需要提醒下:迭代器对象一定是可迭代对象,而可迭代对象不一定是迭代器对象!

迭代器例1:可迭代对象

复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-

#迭代器协议例子
t01=[122,44]
t02=t01.__iter__()
print(t02.__next__())
print(t02.__next__())
View Code
复制代码

代码运行结果:

122

44

迭代器例2:可迭代对象

复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-

dic01={"name":"licy","age":12}
diedai01=dic01.__iter__()
print(diedai01.__next__())
print(diedai01.__next__())
View Code
复制代码

代码运行结果:

age
name

for循环机制

  for循环也是基于遵循迭代器协议!

next()方法

next()方法:实际上就是调用对象的可迭代对象next方法
例1:
复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-

#next()方法:实际上就是调用对象的可迭代对象next方法
t01=[1,2,3]
l=t01.__iter__()
print(l.__next__())
print(l.__next__())
print(l.__next__())
View Code
复制代码

代码执行结果:

1

2

3

例2:

复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-

#next()方法:实际上就是调用对象的可迭代对象next方法
t01=[1,2,3]
l=t01.__iter__()
print(next(l))
print(next(l))
print(next(l))
View Code
复制代码

代码执行结果:与例子结果相同

1

2

3

posted on   永远的大空翼  阅读(48)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示