Iterator

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

An iterator is an object that remembers where the traversal is.

The iterator object is accessed from the first element of the collection until all elements are accessed. The iterator can only move forward and not back.

The iterator has two basic methods: iter() and next().

Strings, lists, or yuan group objects can all 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:

#!/usr/bin/python3

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

To execute the above procedure, the output is as follows:

1 2 3 4

You can also use the next() function:

#!/usr/bin/python3

import sys         # 引入 sys 模块

list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象

while True:
    try:
        print (next(it))
    except StopIteration:
        sys.exit()

To execute the above procedure, the output is as follows:

1
2
3
4

The generator

In Python, a function that uses yield is called a generator.

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

During the call generator run, each time the yield is encountered, the function pauses and saves all current run information, returning the value of the yield. and continue to run from the current position the next time the next() method is executed.

The following example uses yield to implement the Fiponachi number column:

#!/usr/bin/python3

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()

To execute the above procedure, the output is as follows:

0 1 1 2 3 5 8 13 21 34 55