当前位置:网站首页>可迭代对象与迭代器、生成器的区别与联系
可迭代对象与迭代器、生成器的区别与联系
2022-07-01 16:31:00 【红烧code】
可迭代对象与迭代器、生成器的区别与联系
可迭代对象
可以用for ... in obj遍历的对象都是可迭代对象(Iterable),分为两类:
- 一类是集合数据类型,如
list、tuple、dict、set、str等; - 一类是
generator,包括生成器和带yield的生成器函数。
所以说可迭代对象包含了生成器。
迭代器
可以被
next()函数调用并不断返回下一个值的对象称为迭代器:Iterator使用
for ... in obj遍历迭代器,实际上是先调用一次iter(obj),后依次调用next(obj),直到遍历完成所以迭代器一定是可迭代对象
判断一个对象是迭代器的必要条件:
__iter__()魔法方法返回的是一个迭代器对象- 定义了
__next__()魔法方法
二者缺一不可
生成器
通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,而且当我们仅仅需要访问前面几个元素,那后面的大多数元素占用的空间都白白浪费了。
所以我们使用生成器一边迭代一边计算是最优的选择,虽然效率会降低,例如:

结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<generator object <genexpr> at 0x000001BE222485F0>
生成器都能使用next()遍历,所以生成器都是迭代器。
from collections import Iterator
y = (i for i in range(10))
print(isinstance(y, Iterator))
print(next(y))
print(next(y))
print(next(y))
结果:
True
0
1
2
总结:

迭代器都是可迭代对象,但是可迭代对象不一定是迭代器
生成器都是迭代器,但是迭代器不一定是生成器
可迭代数据类型
list、str、dict等都是可迭代对象Iterable但不是迭代器Iterator,不过可以通过iter(list)函数获取一个迭代器对象x=iter("hjdyyds") print(x) print(next(x)) print(next(x)) print(next(x)) print(next(x))结果:
<str_iterator object at 0x0000017FA3A8CC70> h j d y可以通过
for ... in obj来遍历,只能说明obj是可迭代对象可以通过
next(obj)遍历,只能说明obj是迭代器判断是否是可迭代对象、迭代器、生成器的通用方法:
from collections import Iterable, Iterator, Generator x = "hjdyyds" print(isinstance(x, Iterable)) print(isinstance(x, Iterator)) print(isinstance(iter(x), Iterator)) print(isinstance(x, Generator))结果:
True False True Falseprint(isinstance(x, Generator))
结果: ```python True False True False- 如果obj可以使用
obj[index]来访问,说明obj是可迭代对象,并且定义了__getitem__()魔法方法
- 如果obj可以使用
边栏推荐
- GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
- 数据库系统原理与应用教程(005)—— yum 离线安装 MySQL5.7(Linux 环境)
- Please, stop painting star! This has nothing to do with patriotism!
- 求求你们,别再刷 Star 了!这跟“爱国”没关系!
- 美国国家安全局(NSA)“酸狐狸”漏洞攻击武器平台技术分析报告
- How to use etcd to realize distributed /etc directory
- Buuctf gold III
- 红队第10篇:coldfusion反序列化过waf改exp拿靶标的艰难过程
- Borui data integrated intelligent observable platform was selected into the "Yunyuan production catalogue" of China Academy of communications in 2022
- Tutorial on the principle and application of database system (001) -- MySQL installation and configuration: installation of MySQL software (Windows Environment)
猜你喜欢

Rhcsa Road

Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)

Redis 分布式鎖

sql刷题1050. 合作过至少三次的演员和导演

【直播预约】数据库OBCP认证全面升级公开课

今天14:00 | 港大、北航、耶鲁、清华、加大等15位ICLR一作讲者精彩继续!

游戏行业安全选择游戏盾,效果怎么样?

数据库系统原理与应用教程(003)—— MySQL 安装与配置:手工配置 MySQL(windows 环境)
![[flask introduction series] cookies and session](/img/2e/d50e0a032c4ec48935cb5df206a29b.png)
[flask introduction series] cookies and session

What is the digital transformation of manufacturing industry
随机推荐
Rhcsa Road
毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?
[live broadcast appointment] database obcp certification comprehensive upgrade open class
如何使用phpIPAM来管理IP地址和子网
Golang爬虫框架初探
阿里云、追一科技抢滩对话式AI
免费抽奖 | 《阿巴豆》探索未来系列盲盒数字版权作品全网首发!
What is the effect of choosing game shield safely in the game industry?
C语言输入/输出流和文件操作
How to optimize repeated if err in go language= Nil template code?
EndeavourOS移动硬盘安装
Research and investment strategy report of China's sodium sulfate industry (2022 Edition)
Why is the pkg/errors tripartite library more recommended for go language error handling?
How to use phpipam to manage IP addresses and subnets
How to repair the laptop that cannot connect to the wireless network
Kali install Nessus
P2592 [ZJOI2008]生日聚会(dp)
China BMS battery management system Market Research Report (2022 Edition)
Advantages, values and risks of chain games compared with traditional games
sql刷题627. 变更性别