当前位置:网站首页>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
边栏推荐
- Soft test software designer full truth simulation question (including answer analysis)
- How to use etcd to realize distributed /etc directory
- (十六)ADC转换实验
- 走进微信小程序
- libcurl下载文件的代码示例
- Please, stop painting star! This has nothing to do with patriotism!
- 【splishsplash】关于如何在GUI和json上接收/显示用户参数、MVC模式和GenParam
- RadHat搭建内网YUM源服务器
- Report on research and investment prospects of UHMWPE industry in China (2022 Edition)
- [Verilog quick start of Niuke network question brushing series] ~ priority encoder circuit ①
猜你喜欢

剑指 Offer 20. 表示数值的字符串

6月刊 | AntDB数据库参与编写《数据库发展研究报告》 亮相信创产业榜单

String的trim()和substring()详解

How wild are hackers' ways of making money? CTF reverse entry Guide

Gameframework eating guide

Iommu/smmuv3 code analysis (10) page table operation

SQL question brushing 584 Looking for user references

Free lottery | explore the future series of blind box digital copyright works of "abadou" will be launched on the whole network!

The amazing open source animation library is not only awesome, but also small

SQL question brushing 586 Customers with the most orders
随机推荐
PETRv2:一个多摄像头图像3D感知的统一框架
Judge whether a binary tree is a balanced binary tree
剑指 Offer 20. 表示数值的字符串
Vulnhub range hacker_ Kid-v1.0.1
中国超高分子量聚乙烯产业调研与投资前景报告(2022版)
Object. fromEntries()
Shenyu gateway development: enable and run locally
官宣!香港科技大学(广州)获批!
In depth evaluation and development trend prediction report of China's ice cream market (2022 Edition)
Computed property “xxx“ was assigned to but it has no setter.
Redis6.0 new features
求求你们,别再刷 Star 了!这跟“爱国”没关系!
Transition technology from IPv4 to IPv6
Free lottery | explore the future series of blind box digital copyright works of "abadou" will be launched on the whole network!
如何写出好代码 — 防御式编程指南
China metallocene polyethylene (MPE) Industry Research Report (2022 Edition)
Detailed explanation of string's trim() and substring()
Why should you consider using prism
【C补充】【字符串】按日期排序显示一个月的日程
SQL question brushing 586 Customers with the most orders