13. Iterators in Python

An iterator is a data stream object or container. When using the data in it, it takes one data from a data stream at a time until the data is fetched, and the data will not be reused;


1. Custom iterator

Implementing a custom iterator requires implementing the following methods:

  • __iter__() : The method returns the object itself, which is a requirement for the for statement to use the iterator;
  • __next()__ : The method returns the next element or data for the container. Raise StopIteration exception when data in container is exhausted

Custom exception example:

#依次遍历X的n次方,知道大于100时结束迭代
class MyIterator:
    def __init__(self, x=2, max=100):
        self.__x = x
        self.__mul = x
        self.__max = max

    # 定义iter函数,返回自身
    def __iter__(self):
        return self

    # 定义next函数,制定迭代器的返回值
    def __next__(self):
        if self.__x != 0 and self.__x != 1:
            self.__mul *= self.__x
            if self.__mul <= self.__max:
                return self.__mul
            else:
                raise StopIteration
        else:
            raise StopIteration

if __name__ == '__main__':
    myItor = MyIterator()
    for i in myItor:
        print(i)

Running result:
4
8
16
32
64

The iterator class must raise a StopIteration error under certain conditions to end the traversal loop, otherwise an infinite loop will occur.


2. Built-in iteration tools

(1), the built-in iteration function iter()

  • iter(iterable) , the parameter is an iterable type, such as various sequences;
  • iter(callable, sentinel) , the first parameter is a callable type, usually a function; the second parameter is called "sentinel", that is, when the return value of the first parameter call is equal to the value of the second parameter, iterative or traversal stop;

Example of built-in function iter():

def function():
    global x
    x += 2
    return x

if __name__ == '__main__':
    lst = [1, 2, 3, 4]
    for i in iter(lst):             #iter()函数一个参数
        print(i, end=' ')
    print()
    x = 0
    for i in iter(function, 12):    #iter()函数两个参数
        print(i, end=' ')

Running result:
1 2 3 4
2 4 6 8 10


(2) Common iterative tools in the itertools module

Common iteration tools in the itertools module are shown in the following table:

Classification function name describe
infinite iteration count(start[, step]) Start from start, iterate with step as the step count
infinite iteration cycle(seq) infinite loop iteration seq
infinite iteration repeat(elem[, n]) loop iteration elem
Iterate over short sequences chain(p, q, …) chain iterations, linking p,q... to iterate as if iterating from a sequence
Iterate over short sequences compress(data, selectors) Select the values ​​in the iterative data sequence based on the values ​​in selectors
Iterate over short sequences dropwhile(pred, seq) When the result of pred processing the sequence element is false, the value after iterating seq starts
Iterate over short sequences filterfalse (pred, seq) Elements when pred handles false
Iterate over short sequences takewhile(pred, seq) Opposite to dropwhile
Iterate over short sequences tee(it, n) Repeat it n times to iterate
Combining iterative sequences product(p, q, …[, n]) Iterate through all sequences
Combining iterative sequences permutations(p, r) permutation of r elements in iterative sequence
Combining iterative sequences combinations(p, r) iterate over combinations of r elements in a sequence

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325588913&siteId=291194637