Python (5) generator, iterator

First, the generator
square

//传统方法 浪费时间
square_table = []
for i in range(10000):
    square_table.append(i*i)
for i in range(10):
    print (square_table[i])

Generators (do the real calculations when they are used, saving time and space)

square_generator = (x*x for x in range(50000))//range(50000)为生成器
for i in range10):
    print(next(square_generator))

Example: Fibonacci sequence

def fib(limit):
    n,a,b = 0,0,1
    while n<limit:
        #print(b)
        yield b
        a,b = b,a+b
        n += 1
    return 'done'
import traceback
f = fib(5)

try:
    print(next(f))
except StopITeration:
    traceback.print_exc()

for i in fib(5):
print(i)

2. The yield keyword
A function with yield is a generator, which is different from ordinary functions. Generating a generator looks like a function call, but will not execute any function code until next() is called on it (in the for loop). will automatically call next()) to start execution. Although the execution flow is still executed according to the flow of the function, it will be interrupted every time a yield statement is executed, and an iteration value will be returned, and the execution will continue from the next statement of yield in the next execution. It looks as if a function is interrupted by yield several times during normal execution, and each interrupt returns the current iteration value through yield.

The benefits of yield are obvious. Rewriting a function into a generator gives it the ability to iterate. Compared with using a class instance to save the state to calculate the value of the next next(), not only the code is concise, but also the execution process is very clear.
For details, see: https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/

How to tell if a function is a special generator function? You can use isgeneratorfunction to judge:

from inspect import isgeneratorfunction 
isgeneratorfunction(fab) 
//True

3. Iterator (lazy calculation, generator is a kind of iterator) The
iterator holds a field of internal state, which is used to record the return value of the next iteration. It implements the next and iter methods, and the iterator will not be one-time Loads all elements into memory, but only generates return results when needed.
So what iterator? It is a stateful object that returns the next value in the container when you call the next() method. Any object that implements iter and next () (next() in python2) is an iterator , iter returns the iterator itself, next returns the next value in the container, and if there are no more elements in the container, a StopIteration exception is thrown, it doesn't matter how they are implemented.

from collections import Iterable
from collections import Iterator
//判断列表和字典是否是可迭代的,结果返回True
print(isinstance([1,2,3],Iterable))//True
print(isinstance({},Iterabel))//True
print(isinstance(123,Iterabel))//False
print(isinstance(‘abc',Iterabel))//True
print(isinstance([1,2,3],Iterator))//数组是可迭代的,但不是可迭代器

g = (x*x for x in range(10))
print(type(g))
print(isinstance(g,Iterable))//True,是可迭代的,便可以用for循环来打印
for i in g:
    print(i)
//判断斐波那契函数是否是迭代器
def fib(limit):
    n,a,b = 0,0,1
    while n<limit:
        #print(b)
        yield b
        a,b = b,a+b
        n += 1
    return 'done'
f = fib(6)
print(type(f))
print(isinstance(f,iterable))//True
print(isinstance(f,iterator))//True
for i in f:
    print(i)

An article with a very detailed explanation is recommended: http://python.jobbole.com/87805/

Guess you like

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