Generators and Iterators

iterative generation

The principle of for loop traversal

The principle of for loop traversal is iteration, and in must be an iterable object

Why have iterators

对于序列类型:字符串、列表、元组,我们可以使用索引的方式迭代取出其包含的元素。但对于字典、集合、文件等类型是没有索引的,若还想取出其内部包含的元素,则必须找出一种不依赖于索引的迭代方式,这就是迭代器

1. Iterable objects

Objects with __iter__methods are all iterable objects, and there are the following 6 types

Iterable objects: Python built-in str, list, tuple, dict, set, and file are all iterable objects

"zx".__iter__()
["zx"].__iter__()
{
      
      "zx":"wl"}.__iter__()
("zx",).__iter__() { 
         "z","x"}.__iter__() with open("prize.txt","r") as file: file.__iter__()

2. Iterator object

1. Iterable object __iter__The return value obtained by executing the method is the iterator object. 2. Iterator objects refer to objects that have both built-in __iter__and built-in __next__methods

list=[1,2,3,4,5,6] zx=list.__iter__() while True: try: print(zx.__next__()) except: break

file type is an iterator object

open('a.txt').__iter__()
open('a.txt').__next__()

An iterator object must be an iterable object, and an iterable object is not necessarily an iterator object

Builder

A generator is a type of iterator. One of the characteristics of iterators is that they can be called by the next() function and continue to return the next value of the object, and can only iterate over them once. The reason is simple, because they are not all stored in memory, they are only generated in memory when they are called.

A generator is an iterator (the result returned by a function is a generator, and it has both __iter__and __next__)

def zx():
    yield 1 yield 2 x=zx() x.__next__() x.__iter__()

laboratory

After each time __next__, the corresponding yield will be executed and the following content will not be executed.

why? This experiment was executed, because he used for, he didn't know where to execute it at the end, he would keep going __next__until the last exception was thrown, but for in comes with the content of catching exceptions, and no exception information was printed.

def func():
    yield [1,1,23] # yield会使函数func()变成生成器对象,因此他就具有__iter__方法 print(789) # yield会停止函数,当运行下一次next才会继续运行下面的代码 yield 101112 # 一个yield对应一个next print(131415) g = func() for i in g: print(i)

[1, 1, 23]
789
101112
131415

The difference between iterators and generators

A generator is a special kind of iterator that implements迭代器协议--iter--,--next--

The generator can change the value of the iteration, but there will be problems with the iterator changing the value at will

The generator needs to handle the exception StopIterationthat there is no iteration value at the end, and the normal iterator has been implemented by default

The difference between iterator and list

list directly loads all data into memory

The iterator takes values ​​one by one, and when the next value is needed, it goes back to calculate and retrieve the value into memory (you can think of the iterator as the code of a generator, next, run the following code, and then return the value)

For in-depth information about iterators, you can check the big guy blog
https://www.cnblogs.com/deeper/p/7565571.html

Reprinted in: https://www.cnblogs.com/whnbky/p/11520533.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326560032&siteId=291194637