python-iterator (next(), iter() function) and generator (yield function)

iterator

Iteration is one of the most powerful features of Python and is a way of accessing the elements of a collection.

An iterator is an object that remembers where to traverse.

迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。

Iterators have two basic methods: iter() and next()

1. Create an iterator object iter()
list_a = [i for i in range(10)]
list_iter_a = iter(list_a)  # 迭代对象
2. Access the iterator element next()
list_a = [i for i in range(10)]
list_iter_a = iter(list_a)  # 迭代对象
print(next(list_iter_a)) # 输出迭代器的下一个元素   0
print(next(list_iter_a)) # 输出迭代器的下一个元素   1
>>>
0
1
3. Create an iterator

Using a class as an iterator requires implementing two methods __iter__() and in the class __next__().

If you already know object-oriented programming, you know that a class has a constructor, and the Python constructor is _ _init__(), which will be executed when the object is initialized.

__iter__() The method returns a special iterator object that implements the __next__()method and marks the completion of the iteration through the StopIteration exception.

__next__() method( next()) returns the next iterator object.

Create an iterator that returns numbers, the initial value is a list of 1-100 and the ID is 0, and the number of the list is processed by *10

python3.x is
class List_num_ride(object):

    def __iter__(self): # 相当于初始化,__init__() ,自我认为
        self.id = 0
        self.list_num = [i for i in range(100)]
        return self

    def __next__(self):
        x = self.list_num[self.id] * 10
        self.id += 1
        return x

my_class = List_num_ride()
myiter = iter(my_class)
print(next(myiter))  # 0*10
print(next(myiter))  # 1*10
print(next(myiter))  # 2*10
print(next(myiter))  # 3*10

>>>
0
10
20
30

Builder------yield

In Python, functions yieldthat are called generators.

Unlike ordinary functions, a generator is a function that returns an iterator and can only be used for iterative operations. It is easier to understand that a generator is an iterator.

在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield的值, 并在下一次执行next() 方法时从当前位置继续运行。

Call a generator function that returns an iterator object

1、next()
def intNum():
    print("开始执行")
    for i in range(5):
        yield i   # <-------,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值,
        print("继续执行")
num = intNum()

print(next(num))
print(next(num))
print(next(num))

>>>
开始执行
0
继续执行
1
继续执行
2
2、 __ next __()

The generator calls the _ next _() method, which has exactly the same function as the next() function. It seems that the bottom layer of the next() function also executes the **_ next _()** method

def intNum():
    print("开始执行")
    for i in range(5):
        yield i   # <-------,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,返回 yield 的值,
        print("继续执行")
num = intNum()
print(num.__next__()) # __next__()是返回下一个迭代对象 ,所以他是直接执行到yield就停止
print(num.__next__())
print(num.__next__())

>>>
开始执行
0
继续执行
1
继续执行
2
StopIteration exception

The StopIteration exception is used to mark the completion of the iteration to prevent an infinite loop. In the next () method, we can set the StopIteration exception to end the iteration after the specified number of cycles is completed.

Generator to write Fibonacci numbers
import sys

def fibonacci(n):  # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n):
            return
        yield a
        a, b = b, a + b
        counter += 1

f = fibonacci(10)  # f 是一个迭代器,由生成器返回生成

while True:
    try:
        print(next(f), end=" ")
    except StopIteration:  # 用来标记本while循环,在print输出完了,没有输出
        sys.exit()
        
>>>
0 1 1 2 3 5 8 13 21 34 55 

insert image description here

Hope this blog post was helpful to you!
Thank you for your likes and comments!

Guess you like

Origin blog.csdn.net/qq_44936246/article/details/126130023