码迷,mamicode.com
首页 > 其他好文 > 详细

关于生成器---(yield)

时间:2018-07-12 12:57:34      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:color   alt   hide   多个   tar   img   自定义   函数   for   

生成器:是自定义的迭代器(自己用python代码写的迭代器),函数中见到yield的就是生成器

那么yield前后的变量又该怎么理解

看例子一

def counter(name):
    print(%s ready to count%name)
    num_list=[]
    while True: #这个语句的作用是循环利用yield,这样的话对象就可以无限传值了
        #yield前的变量是接收值的
        num=yield 现在的列表是%s%num_list #yield后面的变量会打印处理
        num_list.append(num)
        print(%s start to count %s%(name,num))

e=counter(xincheng)
print(e.send(None)) #或者 next(e)
print(e.send(1))
print(e.send(2))
for i in range(3,10):
    print(e.send(i))

例子一打印结果为:

技术分享图片
xincheng ready to count
现在的列表是[]
xincheng start to count 1
现在的列表是[1]
xincheng start to count 2
现在的列表是[1, 2]
xincheng start to count 3
现在的列表是[1, 2, 3]
xincheng start to count 4
现在的列表是[1, 2, 3, 4]
xincheng start to count 5
现在的列表是[1, 2, 3, 4, 5]
xincheng start to count 6
现在的列表是[1, 2, 3, 4, 5, 6]
xincheng start to count 7
现在的列表是[1, 2, 3, 4, 5, 6, 7]
xincheng start to count 8
现在的列表是[1, 2, 3, 4, 5, 6, 7, 8]
xincheng start to count 9
现在的列表是[1, 2, 3, 4, 5, 6, 7, 8, 9]
例子一结果

 例子二:

def counter(name):
    print(%s ready to count%name)
    num_list=[]
    while True:
        num=yield num_list,hehe #yield后面的变量会答应处理,多个用,隔开,结果就会放入一个元组中
        num_list.append(num)
        print(%s start to count %s%(name,num)) #yield后面的语句一般为下一个yield的开始

e=counter(xincheng)
next(e)
s=e.send(1) #xincheng start to count 1
print(s,type(s)) #([‘1‘], ‘hehe‘) <class ‘tuple‘> yield后面的东西是给对象传的值,多个值放在一个元组中

 

关于生成器---(yield)

标签:color   alt   hide   多个   tar   img   自定义   函数   for   

原文地址:https://www.cnblogs.com/mmyy-blog/p/9298076.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!