Python base (XVI): iterators and generators

table of Contents

1 iterators

Iteration

We know that there are some objects Python can forto loop through, for example: a list of tuples, characters, etc., a string, for example, as follows:

for i in 'Hello':
    print(i)

Results of the:

H
e
l
l
o

The traversal process is iterative.

Iterables

Iterables need to have __iter__()methods that can be used forto loop through, we can use the isinstance()method to determine whether an object is iterables, see next example:

from collections import Iterable

print(isinstance('abc', Iterable))
print(isinstance({1, 2, 3}, Iterable))
print(isinstance(1024, Iterable))

Results of the:

True
True
False

Iterator

Iterators need to have __iter__()and __next__()two methods, the two methods together form the iterator protocol, popular terms iterator is a traverse position of the object can remember, the iterator must be iterative, not vice versa.

  • __iter__(): Returns an iterator object itself
  • __next__(): Returns the next data

Nature object iterator is a data stream, it is by constantly calling __next__()method or the built-in next()call returns the next data method, thrown when there is no next data StopIterationends abnormally iteration. We said above forto achieve the cycle statement is the use of iterators.

We try to achieve their own iterator as follows:

class MyIterator:
    def __init__(self):
        self.s = '程序之间'
        self.i = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.i < 4:
            n = self.s[self.i]
            self.i += 1
            return n
        else:
            raise StopIteration

mi = iter(MyIterator())
for i in mi:
    print(i)

Output:


2 Builder

Builder is a tool for creating iterators, whose wording is similar to a standard function, except that using the return yieldstatement about yield, we use Scrapy climb to take away Netscape area where information has been some introduction, let's familiar a bit:

yield is a key role and return about the same, the difference is that yield returns a generator (in Python, while circulation mechanism side of computing, known as a generator), its role is to: help reduce the server resources, in the list of all data in memory, and a process corresponding to the generator rather than specific information, how much to take many small memory.

There are many ways to create a generator, such as: the use of yieldstatements, generator expression (can be simply understood as the list of []replaced (), and there is more concise, but less flexible). Facie example:

Example 1

def reverse(data):
    for i in range(len(data)-1, -1, -1):
        yield data[i]
for char in reverse('Hello'):
    print(char)

Results of the:

o
l
l
e
H

Example 2

# 列表
lis = [x*x for x in range(5)]
print(lis)

# 生成器
gen = (x*x for x in range(5))
for g in gen:
    print(g)

Results of the:

[0, 1, 4, 9, 16]
0
1
4
9
16

Reference:
https://docs.python.org/zh-cn/3/tutorial/classes.html#iterators


Published 44 original articles · won praise 953 · views 130 000 +

Guess you like

Origin blog.csdn.net/ityard/article/details/103897131