当前位置:网站首页>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、stretc. ; - One is
generator, Including generator and beltyieldThe 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 :IteratorUse
for ... in objErgodic 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、dictAnd so on are all iterable objectsIterableBut 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 yCan pass
for ... in objTo 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 Falseprint(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
边栏推荐
- String的trim()和substring()详解
- [pyg] document summary and project experience (continuously updated
- 6月刊 | AntDB数据库参与编写《数据库发展研究报告》 亮相信创产业榜单
- (12) About time-consuming printing
- Introduction to software engineering - Chapter 6 - detailed design
- 字节跳动数据平台技术揭秘:基于 ClickHouse 的复杂查询实现与优化
- In depth evaluation and development trend prediction report of China's ice cream market (2022 Edition)
- Integer array merge [JS]
- 换掉UUID,NanoID更快更安全!
- 【Try to Hack】vulnhub DC4
猜你喜欢

Redis6.0 new features

多线程并发之CountDownLatch阻塞等待

National Security Agency (NSA) "sour Fox" vulnerability attack weapon platform technical analysis report

Mysql database - Advanced SQL statement (2)

Machine learning 11 clustering, outlier discrimination

Soft test network engineer full truth simulation question (including answer and analysis)

SQL question brushing 584 Looking for user references

There is a new breakthrough in quantum field: the duration of quantum state can exceed 5 seconds
![Integer array merge [JS]](/img/0d/70535e0eb1c299bda25159b58c70d7.png)
Integer array merge [JS]

String的trim()和substring()详解
随机推荐
LeetCode中等题之TinyURL 的加密与解密
阿里云李飞飞:中国云数据库在很多主流技术创新上已经领先国外
求求你们,别再刷 Star 了!这跟“爱国”没关系!
中国氮化硅陶瓷基板行业研究与投资前景报告(2022版)
Sword finger offer II 015 All modifiers in the string
多线程使用不当导致的 OOM
荣威 RX5 的「多一点」产品策略
中国茂金属聚乙烯(mPE)行业研究报告(2022版)
Babbitt | yuan universe daily must read: Naixue coin, Yuan universe paradise, virtual stock game Do you understand Naixue's tea's marketing campaign of "operation pull full"
Gameframework eating guide
ACL 2022 | 分解的元学习小样本命名实体识别
Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
反射型XSS漏洞
Soft test software designer full truth simulation question (including answer analysis)
FRP intranet penetration, reverse proxy
Detailed explanation of string's trim() and substring()
如何写出好代码 — 防御式编程指南
SQL question brushing 627 Change gender
Sword finger offer 20 String representing numeric value
The amazing open source animation library is not only awesome, but also small