Seven, python iterators and generators

Iterator

Comprising ITER () method or getitem Object () method called 可迭代对象.

迭代器协议Refers to an object to be provided ITER () and the __next __ () method, wherein, ITER () method returns an iterator object itself, next method returns the next element of the container (), raise StopIteration in the absence of subsequent elements.
This agreement is in line with the object can be called 迭代器.

The essence of the for loop to get an iterator through the built-in function iter iterable of (), and then continue to call the iterator's next () function implementation elements to obtain container.

for x in [1, 2, 3]:
    print i
#=====等价于=====
# 获得 Iterator 对象
it = iter([1, 2, 3])

# 循环
while True:
    try:
        # 获得下一个值
        x = next(it)
        print x
    except StopIteration:
        # 没有后续元素,退出循环
        break

Creating an iterator

class MyNumbers:

    def __init__(self):
        self.a,self.b=0,1
    def __iter__(self):
        return self
    def __next__(self):

        self.a,self.b=self.b,self.a+self.b
        return self.a

myclass = MyNumbers()
for i in myclass:
    if i <10:
        print(i)
    else:
        break

Builder

Builder also follows the iterator protocol, so it is an iterator.
There are two ways to build generator:

  1. Generator function: function definition routine, except that instead of the yield statement return statement return results. a yield statement returns a result, in the middle of each result, the pending status of the function, so that the next resumes where it left off.
  2. Generator expression: deriving a list of similar, but returns an object generator demand produce a result, rather than a one to build a list of results.

Generator expressions are generated, and a generator function generator object, each object takes to generate a target element and does not output all at once.

Because the generator function, is a function of a stronger structure, so when using the basic generator, or in the main generator function.

Creating a simple generator

def generator1():
    print ('hello 1')
    yield 1
    print ('hello 2')
    yield 2
    print('hello 3')

g = generator1()  # 函数没有执行,而是返回了一个生成器,当然也是一个迭代器
a=next(g)  # 当使用 next(g)时,函数体开始执行,遇到 yield 暂停,yield返回1给a
print(a)
b=next(g)    #从原来暂停的地方继续执行
print(b)
next(g)    # 从原来暂停的地方继续执行,没有遇到yield,抛出异常StopIteration

##输出结果如下:
#hello 1
#1
#hello 2
#2
#hello 3
#Traceback (most recent call last):
#StopIteration

Create a generator function generator function of the course is to continually look to execute -> break -> Execution -> process interruption.next使得生成器接着上次中断的地方继续执行,生成器执行到yield则函数中断并返回一个值

Demonstrates a for loop generator

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1

f=fib(6)##fib函数中使用了yield,那么fib()函数便成为一个生成器,为max=6时的生成器命名为f。
print(f)##打印生成器f的内存单元

for i in f:
    print(i)
##通过循环生成器,将生成器中的数据取出,函数fib不会一次性生成所有数据,每次循环遇到yield中断返回,并返回一次b的值

send method Builder'
Send () method on that next () function, is added to the traditional values yield.

def generator2():
    value1 = yield 0 ##对于有=的代码执行顺序是先执行等号右边的代码,遇到yield则暂停执行将后面 0返回
    print('value1 is ', value1)
    value2 = yield 1 ##对于有=的代码执行顺序是先执行等号右边的代码,遇到yield则暂停执行将后面 1返回
    print('value2 is ', value2)
    value3 = yield 2
    print('value3 is ', value3)

g = generator2()
a=next(g)   # 调用next()开始执行,返回 0
print(a)
b=g.send(2) #相当于调用next,从上次暂停的地方继续执行并将2传递给yield
print(b)
g.send(3)

Simulation generators with a producer - consumer Scene

import time
def consumer(name):
    print("%s 准备吃包子啦!" %name)
    while True:
       baozi = yield  ##此处代码可以理解为先执行等号右边,在左边
       print("包子[%s]来了,被[%s]吃了!" %(baozi,name))

##定义一种consumer生成器

def producer():
    c = consumer('A')  ##为A做一个consumer生成器c
    c.__next__()   ##调用一次A的consumer生成器c,使用生成器时遇到yield中断返回
    print("开始准备做包子啦!")
    for i in range(4):
        time.sleep(1)
        print("做了1个包子!")
        c.send(i)
    ##做一个循环,通过send方法调用生成器c,send方法将i的值传送给yield,在生成器中baozi的值指向yield

producer()

##输出结果如下:
A 准备吃包子啦!
开始准备做包子啦!
做了1个包子!
包子[0]来了,[A]吃了!
做了1个包子!
包子[1]来了,[A]吃了!
做了1个包子!
包子[2]来了,[A]吃了!
做了1个包子!
包子[3]来了,[A]吃了!
发布了40 篇原创文章 · 获赞 2 · 访问量 2060

Guess you like

Origin blog.csdn.net/weixin_42155272/article/details/93879973