Centos中Python3的生成器应用

生成器:利用有顺序或者递归的数列,列表,数组形成的函数,并能逐级往下打印,这是我理解的生成器。

Centos中Python3的生成器应用

图片中的参数g就是一个生成器generator,对应着计算机的排序的在编码的0x7f***

每次使用一次next函数就生成一个结果。

Centos中Python3的生成器应用

只要是一个生成器,我们就可以用for循环对着每个生成的结果取参,在将结果打印出来。(同时for循环也是验证生成器方法))

 

生成器的两种使用方法:

Centos中Python3的生成器应用

实例:演示利用生成器的方法传送参数给函数,在打印输出

[[email protected] 十九天]# cat test05.py   #创建一个文件。
def gen(times):
    n=0
    while n < times:
        temp=yield n*3
        print(temp)
        n=n+1
    return "done"

 

[[email protected] 十九天]# ipython3   #启动ipython3编辑器,将模块导入测试。
/usr/python-3.4.6/lib/python3.4/site-packages/IPython/core/history.py:226: UserWarning: IPython History saved
  warn("IPython History requires SQLite, your history will not be saved")
Python 3.4.6 (default, Jan 24 2019, 11:20:45) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from test05 import *

In [2]: g=gen(5)  #将生成器赋予变量g

In [3]: g.send(None)#使用生成器的方法1
Out[3]: 0

In [4]: g.send("heh")   #使用生成器的方法2,注意第一次传参数是系统不支持,有兴趣同学可以试一试;必须先传其他参数才能用Send方法。
heh
Out[4]: 3

In [5]: globles

总结:生成器好比有个递归序列赋予一个变量中,每次可以使用这个变量的__init__方法,或者是x.send(*)方法。