生成器与迭代器

生成器:只有在调用的时候才会生成相应的数据

              只能逐个往后取(不能取前面的,也不能直接跳到后面)

              只有一个__next()__方法(Python3)next()(Python2)

两种实现方式

1.生成器表达式,语法看似列表推导式,只是把最外层的中括号改为小括号。

>>> 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.函数(通过yield关键字)

#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):
    # 斐波拉契数列
    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

迭代器

猜你喜欢

转载自www.cnblogs.com/allenzhang-920/p/8922662.html