Python_生成器(generator)

2018-01-20  本文已影响0人  射手再见蓝天575

generator与list比较

创建一个简单的generator

g=(x*x for x in range(10))

创建一个函数形式的generator

 >>> def yhsj():
    L=[1]
    while True:
        yield L
        L=[1]+[L[i]+L[i+1] for i in range(len(L)-1)]+[1]

      
>>> def get_yhsj():
    for n in yhsj():
        print(n)

      
>>> get_yhsj()
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]
...

函数型的generator与普通函数的不同

上一篇下一篇

猜你喜欢

热点阅读