Generators and Iterators

Generator: The corresponding data will only be generated when it is called

              You can only take it back one by one (you can't take the previous one, and you can't directly jump to the back)

              There is only one __next()__ method (Python3) next() (Python2)

two implementations

1. Generator expression, the syntax looks like a list comprehension, but the outermost square brackets are changed to parentheses.

>>> a = (i for i in range(8))
>>> a
<generator object <genexpr> at 0x000001D1C9FB8A98>
>>> dir(a)
['__class__', '__del__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', ','__iter__'__le__', '__lt__', '__name__', '__ne__', '__new__', '__next__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw']

2. Function (via the yield keyword)

#coding=utf-8

def natural_number():
    '''自然数'''
    n = 0
    while True:
        yield n
        n += 1

n = natural_number()
print n.next()
print n.next()
print n.next()
print n.next()
print n.next()

0
1
2
3
4
#coding=utf-8
    
def fib(x):
     #Fibonacci sequence
    n, a, b = 0, 0, 1
    while n < x:
        yield b
        a, b = b, a + b
        n += 1

f = fib(6)
print f.next()
print f.next()
print f.next()
print f.next()
print f.next()
print f.next()

1
1
2
3
5

 

iterator

 

Guess you like

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