当前位置:网站首页>可迭代对象与迭代器、生成器的区别与联系
可迭代对象与迭代器、生成器的区别与联系
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 False
print(isinstance(x, Generator))
结果: ```python True False True False
- 如果obj可以使用
obj[index]
来访问,说明obj是可迭代对象,并且定义了__getitem__()
魔法方法
- 如果obj可以使用
边栏推荐
- Leetcode 77 combination -- backtracking method
- Please, stop painting star! This has nothing to do with patriotism!
- UML tourism management system "suggestions collection"
- Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
- Hi Fun Summer, play SQL planner with starrocks!
- 数据库系统原理与应用教程(003)—— MySQL 安装与配置:手工配置 MySQL(windows 环境)
- Template Engine Velocity Foundation
- SystemVerilog-结构体(二)
- 判断链表是否是回文链表
- Is the programmer's career really short?
猜你喜欢
SQL question brushing 627 Change gender
Authentication processing in interface testing framework
[pyg] document summary and project experience (continuously updated
Redis 分布式鎖
Transition technology from IPv4 to IPv6
Tutorial on the principle and application of database system (003) -- MySQL installation and configuration: manually configure MySQL (Windows Environment)
[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting
软件工程导论——第六章——详细设计
Girls who want to do software testing look here
Tutorial on the principle and application of database system (001) -- MySQL installation and configuration: installation of MySQL software (Windows Environment)
随机推荐
Concatenate strings to get the result with the smallest dictionary order
China benzene hydrogenation Market Research and investment forecast report (2022 Edition)
How to repair the laptop that cannot connect to the wireless network
Rhcsa Road
How wild are hackers' ways of making money? CTF reverse entry Guide
Origin2018 installation and use (sorting)
[jetsonnano] [tutorial] [introductory series] [III] build tensorflow environment
阿里云、追一科技抢滩对话式AI
数据库系统原理与应用教程(006)—— 编译安装 MySQL5.7(Linux 环境)
Are you still using charged document management tools? I have a better choice! Completely free
今天14:00 | 港大、北航、耶鲁、清华、加大等15位ICLR一作讲者精彩继续!
sql刷题627. 变更性别
[live broadcast appointment] database obcp certification comprehensive upgrade open class
巴比特 | 元宇宙每日必读:奈雪币、元宇宙乐园、虚拟股票游戏...奈雪的茶这波“操作拉满”的营销活动你看懂了吗?...
Tutorial on the principle and application of database system (002) -- MySQL installation and configuration: MySQL software uninstallation (Windows Environment)
China sorbitol Market Forecast and investment strategy report (2022 Edition)
判断链表是否是回文链表
判断二叉树是否为二叉搜索树
How to cancel automatic search and install device drivers for laptops
Golang爬虫框架初探