当前位置:网站首页>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
边栏推荐
- Is it safe to open an ETF account online? What are the steps?
- China biodegradable plastics market forecast and investment strategy report (2022 Edition)
- The difference between the lazy mode of singleton mode and the evil mode
- FRP intranet penetration, reverse proxy
- Research Report on development prediction and investment direction of nylon filament sewing thread in China (2022 Edition)
- Please, stop painting star! This has nothing to do with patriotism!
- The reviewboard has 500 errors when submitting a review. Solutions
- ACL 2022 | 分解的元学习小样本命名实体识别
- 6月刊 | AntDB数据库参与编写《数据库发展研究报告》 亮相信创产业榜单
- Detailed explanation of string's trim() and substring()
猜你喜欢
【牛客网刷题系列 之 Verilog快速入门】~ 优先编码器电路①
Shenyu gateway development: enable and run locally
Countdownlatch blocking wait for multithreading concurrency
存在安全隐患 起亚召回部分K3新能源
【C补充】【字符串】按日期排序显示一个月的日程
Yyds dry inventory MySQL RC transaction isolation level implementation
Free lottery | explore the future series of blind box digital copyright works of "abadou" will be launched on the whole network!
vulnhub靶场-hacksudo - Thor
How to use JMeter function and mockjs function in metersphere interface test
为什么你要考虑使用Prisma
随机推荐
中国茂金属聚乙烯(mPE)行业研究报告(2022版)
vulnhub靶场-hacksudo - Thor
China biodegradable plastics market forecast and investment strategy report (2022 Edition)
Introduction to software engineering - Chapter 6 - detailed design
Shenyu gateway development: enable and run locally
荣威 RX5 的「多一点」产品策略
China sorbitol Market Forecast and investment strategy report (2022 Edition)
How to use etcd to realize distributed /etc directory
[Verilog quick start of Niuke network question brushing series] ~ priority encoder circuit ①
Vulnhub range hacksudo Thor
Replace UUID, nanoid is faster and safer!
Gold, silver and four want to change jobs, so we should seize the time to make up
[C language supplement] judge which day tomorrow is (tomorrow's date)
Roewe rx5's "a little more" product strategy
The amazing open source animation library is not only awesome, but also small
Maizeer: the two batches of products reported by the media have been taken off the shelves and sealed, and consumer appeals are accepted
(28) Shape matching based on contour features
换掉UUID,NanoID更快更安全!
Pytest learning notes (13) -allure of allure Description () and @allure title()
反射型XSS漏洞