当前位置:网站首页>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 object
Iterator 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
边栏推荐
- WinForm(五)控件和它的成员
- 详谈二叉搜索树
- [Server data recovery] Data recovery case of lvm information and VXFS file system corruption caused by raid5 crash
- 微信小程序通过URL Scheme动态的渲染数据
- 使用 BeanUtils 做属性拷贝,性能有点拉胯!
- 【mysql】mysql分别按年/月/日/周分组统计数据
- [GXYCTF2019]BabySQli
- ABP中的数据过滤器
- 20张图,全面掌握MVCC原理!
- Sub-database sub-table ShardingSphere-JDBC notes arrangement
猜你喜欢
使用mysql语句操作数据表(table)
apache+PHP+MySQL+word press, page error when installing word press?
微服务概念
编程技巧│selenium 更新 chromedriver 驱动
Dual machine thermal for comprehensive experiment (VRRP + OSPF + + NAT + DHCP + VTP PVSTP + single-arm routing)
【服务器数据恢复】raid5崩溃导致lvm信息和VXFS文件系统损坏的数据恢复案例
Use mysql statement to operate data table (table)
Data Filters in ABP
EPro-PnP: Generalized End-to-End Probabilistic Perspective-n-Points for Monocular Object Pose Est...
Shell 文本三剑客 Sed
随机推荐
Elastic scaling of construction resources
Mysql database installation and configuration detailed tutorial
The SAP ABAP JSON format data processing
力扣------值相等的最小索引
16. Sum of the nearest three numbers
【openpyxl】过滤和排序
How to easily obtain the citation format of references?
ABP中的数据过滤器
Single-chip human-computer interaction--matrix key
LeetCode_优先级队列_692.前K个高频单词
20张图,全面掌握MVCC原理!
22/8/9 贪心问题合集
Two-dimensional array combat project -------- "Minesweeper Game"
成功解决raise TypeError(‘Unexpected feature_names type‘)TypeError: Unexpected feature_names type
url转成obj或者obj转成url的方法
SystemVerilog: Verifying knowledge bits and pieces
Ambari迁移Spark2到其它机器(图文教程)
全排列思路详解
力扣------使用最小花费爬楼梯
SQL语句--获取数据库表信息,表名、列名、描述注释等