当前位置:网站首页>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
边栏推荐
- In depth evaluation and development trend prediction report of China's ice cream market (2022 Edition)
- [wrung Ba wrung Ba is 20] [essay] why should I learn this in college?
- SQL question brushing 584 Looking for user references
- National Security Agency (NSA) "sour Fox" vulnerability attack weapon platform technical analysis report
- 中国茂金属聚乙烯(mPE)行业研究报告(2022版)
- 如何使用 etcd 实现分布式 /etc 目录
- Research Report on China's enzyme Market Forecast and investment strategy (2022 Edition)
- 【C语言补充】判断明天是哪一天(明天的日期)
- Encryption and decryption of tinyurl in leetcode
- Radhat builds intranet Yum source server
猜你喜欢

DNS

Technical secrets of ByteDance data platform: implementation and optimization of complex query based on Clickhouse

【C补充】【字符串】按日期排序显示一个月的日程
![[Verilog quick start of Niuke network question brushing series] ~ priority encoder circuit ①](/img/24/23f6534e2c74724f9512c5b18661b6.png)
[Verilog quick start of Niuke network question brushing series] ~ priority encoder circuit ①

Detailed explanation of string's trim() and substring()

Redis Distributed Lock

Iommu/smmuv3 code analysis (10) page table operation

PETRv2:一个多摄像头图像3D感知的统一框架

多线程并发之CountDownLatch阻塞等待

Sword finger offer 20 String representing numeric value
随机推荐
PHP实现敏感词过滤系统「建议收藏」
PETRv2:一个多摄像头图像3D感知的统一框架
JDBC:深入理解PreparedStatement和Statement[通俗易懂]
String class
The difference between the lazy mode of singleton mode and the evil mode
中国PBAT树脂市场预测及战略研究报告(2022版)
中国乙腈市场预测与战略咨询研究报告(2022版)
字节跳动数据平台技术揭秘:基于 ClickHouse 的复杂查询实现与优化
智能运维实战:银行业务流程及单笔交易追踪
[C language supplement] judge which day tomorrow is (tomorrow's date)
JDBC: deep understanding of Preparedstatement and statement[easy to understand]
LeetCode中等题之TinyURL 的加密与解密
Oom caused by improper use of multithreading
Computed property “xxx“ was assigned to but it has no setter.
DNS
China BMS battery management system Market Research Report (2022 Edition)
中国锦纶长丝缝纫线发展预测与投资方向研究报告(2022版)
[wrung Ba wrung Ba is 20] [essay] why should I learn this in college?
Develop those things: easycvr cluster device management page function display optimization
MySQL learning summary