当前位置:网站首页>The iterator and generator
The iterator and generator
2022-08-11 01:13:00 【qq_42052864】
Iterable object iterable
1. An object that satisfies the following conditions can become an iterable object
- Object implements __iter__ method
- __iter__ object becomes iterable object
2. Features of iterable objects:
- You can traverse and read data through for .. in .. statements.
- [The working principle of the for loop: internally call the __iter__ method on the iterable object, after obtaining the iterator object, call the __next__ method through the iterator object again and again to obtain the iteration result]
3. Determine whether the object is iterable:
- isinstance(object, Iterable) Iterable: iterable object
- Iterable objects: strings, lists, tuples, dictionaries, sets
from collections.abc import Iterableprint(isinstance(123, Iterable)) # False means it is not an iterable objectprint(isinstance('python', Iterable)) # True represents an iterable objectprint(isinstance({'name':'zs'}, Iterable)) # True represents an iterable objectIterator iterator
Iterator has two functions: iter() and next()Obtain the iterator of the iterable object through the iter() function, continuously use the next() function for the obtained iterator object to obtain the next piece of data, and use next() to raise the StopIteration exception after the elements are retrieved.
# Example 1li = ['Confused', 'SpongeBob', 'Xiaobai'] # The list is an iterable object# create iterator objectname_li = iter(li)print(next(name_li))print(next(name_li))print(next(name_li))print(next(name_li)) # StopIterationExample 2: Custom iterator classclass Test2:def __iter__(self): # This method returns an iterator objectself.n = 1return self # Returns self, indicating that the instance object itself is its own iterator objectdef __next__(self):self.n += 1return self.nte2 = Test2()print(te2) # te2 has the same address as my# print(next(te2)) # AttributeError: 'Test2' object has no attribute 'n'# te2 uses the next method to report an error because the iter method is not called, and the self.n instance attribute inside is not generatedmy = iter(te2) # will call the __iter__ methodprint(next(my)) # 2print(next(my)) #3print(next(my)) #4# Use the same effect of the for loop, the for loop will automatically call the iter method, and then call the next methodfor i in te2:if i <=10:print(i)else:break# Example 3:class Test3:def __init__(self):self.n = 1def __iter__(self):return self # returns the instance object of the current iterator classdef __next__(self):self.n += 1if self.n == 10:raise StopIteration('terminated, can't continue running')return self.nte3 = Test3()try:while True:print(te3.__next__())except StopIteration as e:print("what",e)Generator
1. A generator is an iterator.The definition method is similar to the list comprehension, just change the [] of the list comprehension to ()2. Generator function: In python, a function that uses yield is called a generatorOrdinary functions, use return for return values; generator functions use yield statementsThe yield statement returns one result at a time, and in the middle of each result, suspends the function so that execution continues from where it left off.The yield effect interrupts the function and saves the interrupted state
list comprehension# li = [i*10 for i in range(3)]# print(li)# Change list comprehension [] to ()li2 = (i*10 for i in range(3)) # generator expressionprint(li2) # at 0x000002105DD1B548>print(next(li2))print(next(li2))print(next(li2))# print(next(li2)) # StopIterationdef funa(val):li = []li.append(val)print('This is a list:', li)funa('a') # This is the list: ['a']funa('b') # This is the list: ['b']funa('c') # This is the list: ['c']# generator functiondef funb():print('---started----')yield 2 # returns a 2 and pauses the functionyield 3yield 4fb = funb() # call the generator function, which returns a generator objectprint(fb) # print(next(fb)) # 2print(next(fb)) #3print(next(fb)) # 4print(next(fb)) # StopIteration 边栏推荐
猜你喜欢

Data Filters in ABP

异常:try catch finally throws throw

两个链表的第一个公共节点——LeetCode

时间戳转换为日期格式、获取当前时间戳
![[GXYCTF2019]BabySQli](/img/8a/7500c0ee275d6ef8909553f34c99cf.png)
[GXYCTF2019]BabySQli

Linux install redis database

rhel7.0解决yum无法使用(system is not registered to Red Hat Subscription Management)

#yyds干货盘点#【愚公系列】2022年08月 Go教学课程 008-数据类型之整型

How to do patent mining, the key is to find patent points, in fact, it is not too difficult

WebView2 通过 PuppeteerSharp 实现RPA获取壁纸 (案例版)
随机推荐
postgresql parameter meaning
How to check if the online query suddenly slows down
BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection Paper Notes
BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection 论文笔记
3d打印出现stl文件物体不是流形,意味着不是水密体...解决办法
apache+PHP+MySQL+word press,安装word press时页面报错?
SystemVerilog: 验证知识点点滴滴
Kunpeng compilation and debugging and basic knowledge of native development tools
@Autowired注入RedisCache报错空指针
Volatile和CAS
Dual machine thermal for comprehensive experiment (VRRP + OSPF + + NAT + DHCP + VTP PVSTP + single-arm routing)
Mysql数据库安装配置详细教程
简陋的nuxt3学习笔记
【ASM】字节码操作 ClassWriter COMPUTE_FRAMES 的作用 与 visitMaxs 的关系
ADC和DAC记录
分库分表ShardingSphere-JDBC笔记整理
Vim take on a window.
20张图,全面掌握MVCC原理!
#yyds Dry Goods Inventory#[Yugong Series] August 2022 Go Teaching Course 008-Integer of Data Types
R语言多元线性回归、ARIMA分析美国不同候选人对经济GDP时间序列影响