美文网首页
python 生成器

python 生成器

作者: 浮华_e823 | 来源:发表于2018-09-04 08:42 被阅读0次

生成器

在Python中,这种一边循环一边计算的机制,称为生成器:generator。

创建生成器方法1

要创建一个生成器,有很多种方法。第一种方法很简单,只要把一个列表生成式的 [ ] 改成 ( )
可以用next(list)打印出来

In [18]: l = [x for x in range(5)]

In [19]: l
Out[19]: [0, 1, 2, 3, 4]

In [20]: l = (x for x in range(5))

In [21]: l
Out[21]: <generator object <genexpr> at 0x7f92fadaed58>
In [22]: next(l)
Out[22]: 0

In [23]: next(l)
Out[23]: 1

In [24]: next(l)
Out[24]: 2

In [25]: next(l)
Out[25]: 3

In [26]: next(l)
Out[26]: 4

In [27]: next(l)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-27-101c36968c6d> in <module>()
----> 1 next(l)

创建生成器方法2

著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:

In [28]: def fib(times):
   ....:     n = 0
   ....:     a,b = 0,1
   ....:     while n<times:
   ....:         print(b)
   ....:         a,b = b,a+b
   ....:         n+=1
   ....:     return 'done'
   ....: 

In [29]: fib(5)
1
1
2
3
5
Out[29]: 'done'

In [30]: def fib(times):
   ....:     n = 0
   ....:     a,b = 0,1
   ....:     while n<times:
   ....:         yield b
   ....:         a,b = b,a+b
   ....:         n+=1
   ....:     return 'done'
   ....: 

In [31]: F = fib(5)

In [32]: next(F)
Out[32]: 1

In [33]: next(F)
Out[33]: 1

In [34]: next(F)
Out[34]: 2

In [35]: next(F)
Out[35]: 3

In [36]: next(F)
Out[36]: 5

In [37]: next(F)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-37-8c2b02b4361a> in <module>()
----> 1 next(F)

相关文章

网友评论

      本文标题:python 生成器

      本文链接:https://www.haomeiwen.com/subject/mlwwwftx.html