Python introductory tutorial | Python iterators and generators

Iterator

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

An iterator is an object that remembers the position of a traversal.

The iterator object starts accessing from the first element of the collection until all elements have been accessed. Iterators can only go forward and not backward.

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

String, list or tuple objects can be used to create iterators:

>>> list=[1,2,3,4]
>>> it = iter(list)    # 创建迭代器对象
>>> print (next(it))   # 输出迭代器的下一个元素
1
>>> print (next(it))
2
>>>

Iterator objects can be traversed using regular for statements:

list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
for x in it:
    print (x, end=" ") # 输出为1行

Executing the above program, the output results are as follows:

1 2 3 4

You can also use the next() function:

import sys         # 引入 sys 模块
 
list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
 
while True:
    try:
        print (next(it), end=" ")
    except StopIteration:
        sys.exit()

Executing the above program, the output results are as follows:

1 2 3 4

create an iterator

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

If you already know object-oriented programming (will be discussed later), you know that every class has a constructor. Python's constructor is init (), which will be executed when the object is initialized.

The iter () method returns a special iterator object that implements the next () method and identifies the completion of the iteration through the StopIteration exception.

The next () method (next() in Python 2) returns the next iterator object.

Create an iterator that returns numbers, starting at 1 and incrementing by 1:

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self
 
  def __next__(self):
    x = self.a
    self.a += 1
    return x
 
myclass = MyNumbers()
myiter = iter(myclass)
 
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
  • Class (Class): Used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. An object is an instance of a class, and we will talk about programming-oriented later.
  • Method: The function defined in the class is defined with the def keyword.
    The execution output is:

1
2
3
4
5

StopIteration

The StopIteration exception is used to mark the completion of iteration to prevent infinite loops. In the next () method, we can set the StopIteration exception to be triggered after completing the specified number of loops to end the iteration.

Stop execution after 10 iterations:

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self
 
  def __next__(self):
    if self.a <= 10:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration
 
myclass = MyNumbers()
myiter = iter(myclass)
 
for x in myiter:
  print(x)

The execution output is:

1
2
3
4
5
6
7
8
9
10

Builder

In Python, functions that use yield are called generators.

yield is a keyword used to define a generator function, which is a special function that gradually produces values ​​during an iterative process rather than returning all results at once.

Different from 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.

When the yield statement is used in a generator function , the execution of the function will be paused and the expression following yield will be returned as the value of the current iteration.

Then, each time you call the generator's next() method or iterate using a for loop, the function continues execution from where it last paused until it encounters a yield statement again. This way, the generator function can gradually produce values ​​without having to calculate and return all results at once.

Calling a generator function returns an iterator object.

Here is a simple example showing the use of generator functions:

def countdown(n):
    while n > 0:
        yield n
        n -= 1
 
# 创建生成器对象
generator = countdown(5)
 
# 通过迭代生成器获取值
print(next(generator))  # 输出: 5
print(next(generator))  # 输出: 4
print(next(generator))  # 输出: 3
 
# 使用 for 循环迭代生成器
for value in generator:
    print(value)  # 输出: 2 1

In the above example, the countdown function is a generator function. It uses the yield statement to gradually generate reciprocal numbers from n to 1. Each time the yield statement is called, the function returns the current reciprocal value and resumes execution from where it was last paused on the next call.

By creating a generator object and iterating over the generator using the next() function or a for loop, we can step by step obtain the values ​​produced by the generator function. In this example, we first use the next() function to obtain the first three reciprocal values, and then obtain the remaining two reciprocal values ​​through a for loop.

The advantage of generator functions is that they can generate values ​​on demand, avoiding generating large amounts of data at once and taking up a lot of memory. In addition, generators can work seamlessly with other iteration tools (such as for loops) to provide a concise and efficient iteration method.

Executing the above program, the output results are as follows:

5
4
3
2
1

The following example uses yield to implement the Fibonacci sequence:

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:
        sys.exit()

Executing the above program, the output results are as follows:

0 1 1 2 3 5 8 13 21 34 55

**Supplement:** Fibonacci sequence, also known as the golden section sequence, was introduced by mathematician Leonardo Fibonacci using rabbit reproduction as an example, so it is also called " "Rabbit Sequence" refers to such a sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34,... This sequence starts from the 3rd item, and each item is equal to the sum of the previous two items.

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/132753190