Python generator (generator) & iterator (Iterator)

Builder & python iterator

Generator (Generator)

List of Formula

List formula used to generate a list, though written expression, but storage is calculated result, the generated list memory size is limited
example:

a = [x ** 2 for x in range(5)]
print(a)

Output:

[0, 1, 4, 9, 16]

Generator (Generator)

Generator can also be used to generate a list, but is saved generator algorithm, in each call nextlist when calculates the results, so the resulting memory size limit will not be
an example:

a = (x ** 2 for x in range(5))
print(a)
for i in range(6):
    print(next(a))

Output:

<generator object <genexpr> at 0x107da7870>
0
1
4
9
16
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
StopIteration

Each call next(), calculate the value of the next element, can not get the value of the front element again until the calculation to the last element, no more elements, throw StopIteration error

Generator function

When the function appears yieldwhen this function becomes a generator function
generator encountered in the implementation of the time yieldwhen pauses and save all of the current operating information, return yieldvalue, and the next performance next()continues to operate from its current location when the method
Example:

def fib(max_n):
    """斐波那契数列生成器"""
    n, a, b = 0, 0, 1
    while n < max_n:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'


def main():
    f = fib(6)
    while True:
        try:
            x = next(f)
            print(x)
        except StopIteration as e:
            print("Generator return value:", e.value)
            break


if __name__ == '__main__':
    main()

Output:

1
1
2
3
5
8
Generator return value: done

Yield effect achieved by concurrency operation in the case of single-threaded

Example:

import time


def consumer(name):
    print("%s开始吃包子了" % name)    
    while True:
        produce = yield                                # 函数在此暂停,等待唤醒
        print("%s吃了第%i笼包子" % (name, produce+1))      # 唤醒后执行


def producer(name):
    c = consumer("A")
    c2 = consumer("B")
    c.__next__()    
    c2.__next__()
    print("%s准备开始生产" % name)
    for i in range(3):
        time.sleep(1)
        print("已经做了%i笼包子" % (i+1))
        c.send(i)                                       # 将i发送给produce,并唤醒函数
        c2.send(i)

producer("C")

Output:

A开始吃包子了
B开始吃包子了
C准备开始生产
已经做了1笼包子
A吃了第1笼包子
B吃了第1笼包子
已经做了2笼包子
A吃了第2笼包子
B吃了第2笼包子
已经做了3笼包子
A吃了第3笼包子
B吃了第3笼包子

C function in producer and consumer c2 in turn calls the function
send()and next()the same can wake up generator, but also to yieldtraditional values

Iterator (iterator)

Iterables (iterable)

It may act directly on the loop for the following two types of data:

  1. A class is a collection of data types, such as a list, tuple, dict, set, str, etc.
  2. One is the generator, comprising a generator and a generator function with a yield
    which can act directly on an object referred to as a for loop iterables

Example:

def fib(max_n):
    """斐波那契数列生成器"""
    n, a, b = 0, 0, 1
    while n < max_n:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'


def main():
    f = fib(6)
    for i in f:
        print(i)


if __name__ == '__main__':
    main()

Output:

1
1
2
3
5
8

Iterator (iterator)

Can be next()called function returns the object and continue to the next value of the iterator is called
generator Iterator objects are, but the list, dict, str although Iterable, Iterator is not
the list, dict, str becomes Iterable Iterator may be used and other iter()functions
example:

a = [1, 2, 3, 4, 5, 6, 7]
b = a.__iter__()
c = iter(a)

print(a, b, c)

Output:

[1, 2, 3, 4, 5, 6, 7] <list_iterator object at 0x11d271f60> <list_iterator object at 0x11d260160>

b, c are a by iterator into
a, b, c can be used for loop:

for i in a:
    print(i)
for i in b:
    print(i)

Consistent results

Compared

Generator (generator) are iterators (iterator), but not necessarily a generator iterator, as well as by iter()become iterator iterable

Guess you like

Origin www.cnblogs.com/dbf-/p/11877251.html