当前位置:网站首页>The difference and relationship between iteratible objects, iterators and generators
The difference and relationship between iteratible objects, iterators and generators
2022-07-01 17:29:00 【Braised code】
Iteratable objects and iterators 、 The difference and connection between generators
Iteratable object
It can be used for ... in obj
The traversal objects are all iteratable objects (Iterable)
, There are two kinds of :
- One is set data type , Such as
list、tuple、dict、set、str
etc. ; - One is
generator
, Including generator and beltyield
The generator function of .
So iteratable objects contain generators .
iterator
Can be
next()
The object that function calls and returns the next value continuously is called an iterator :Iterator
Use
for ... in obj
Ergodic iterator , It's actually calling onceiter(obj)
, after successively callnext(obj)
, Until the traversal is completetherefore Iterators must be iterative objects
A necessary condition for judging that an object is an iterator :
__iter__()
The magic method returns an iterator object- Defined
__next__()
Magic methods
You can't have one without the other
generator
Generated by list , We can create a list directly . however , Limited by memory , List capacity must be limited . and , Create a containing 100 List of ten thousand elements , Not only takes up a lot of storage space , And when we only need to access the first few elements , The space occupied by most of the later elements is wasted .
Therefore, it is the best choice for us to use the generator to iterate while calculating , Although the efficiency will be reduced , for example :

result :
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<generator object <genexpr> at 0x000001BE222485F0>
Generators can use next()
Traverse , therefore Generators are iterators .
from collections import Iterator
y = (i for i in range(10))
print(isinstance(y, Iterator))
print(next(y))
print(next(y))
print(next(y))
result :
True
0
1
2
summary :
Iterators are iteratable objects , But iteratable objects are not necessarily iterators
Generators are iterators , But iterators are not necessarily generators
Iteratable data types
list、str、dict
And so on are all iterable objectsIterable
But it's not an iteratorIterator
, But it can go throughiter(list)
Function to get an iterator objectx=iter("hjdyyds") print(x) print(next(x)) print(next(x)) print(next(x)) print(next(x))
result :
<str_iterator object at 0x0000017FA3A8CC70> h j d y
Can pass
for ... in obj
To traverse , Can only explain obj Is an iterable objectCan pass
next(obj)
Traverse , Can only explain obj Is the iteratorDetermine whether it is an iterative object 、 iterator 、 General method of generator :
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))
result :
True False True False
print(isinstance(x, Generator))
result : ```python True False True False
- If obj have access to
obj[index]
To visit , explain obj Is an iterable object , And it defines__getitem__()
Magic methods
- If obj have access to
边栏推荐
- LeetCode中等题之TinyURL 的加密与解密
- SQL注入漏洞(Mysql与MSSQL特性)
- 中国乙腈市场预测与战略咨询研究报告(2022版)
- Detailed explanation of string's trim() and substring()
- Report on research and investment prospects of UHMWPE industry in China (2022 Edition)
- Why should you consider using prism
- SQL injection vulnerability (MySQL and MSSQL features)
- Redis6.0 new features
- 阿里云李飞飞:中国云数据库在很多主流技术创新上已经领先国外
- Petrv2: a unified framework for 3D perception of multi camera images
猜你喜欢
SQL question brushing 627 Change gender
机器学习11-聚类,孤立点判别
Petrv2: a unified framework for 3D perception of multi camera images
Redis6.0 new features
Pytest learning notes (13) -allure of allure Description () and @allure title()
String class
为什么你要考虑使用Prisma
The amazing open source animation library is not only awesome, but also small
SQL question brushing 584 Looking for user references
Official announcement! Hong Kong University of science and Technology (Guangzhou) approved!
随机推荐
How to use JMeter function and mockjs function in metersphere interface test
中国一次性卫生用品生产设备行业深度调研报告(2022版)
英特尔开源深度学习工具库 OpenVINO,将加大与本土软硬件方合作,持续开放
【splishsplash】关于如何在GUI和json上接收/显示用户参数、MVC模式和GenParam
在MeterSphere接口测试中如何使用JMeter函数和MockJS函数
开发那些事儿:EasyCVR集群设备管理页面功能展示优化
unity3d扩展工具栏
Official announcement! Hong Kong University of science and Technology (Guangzhou) approved!
SQL question brushing 1050 Actors and directors who have worked together at least three times
Reflective XSS vulnerability
中国冰淇淋市场深度评估及发展趋势预测报告(2022版)
Judge whether a binary tree is a balanced binary tree
走进微信小程序
Determine whether the linked list is a palindrome linked list
Vulnhub range hacksudo Thor
Jojogan practice
In depth evaluation and development trend prediction report of China's ice cream market (2022 Edition)
Free lottery | explore the future series of blind box digital copyright works of "abadou" will be launched on the whole network!
深度优先遍历和广度优先遍历[通俗易懂]
Please, stop painting star! This has nothing to do with patriotism!