关于生成器---(yield)

生成器:是自定义的迭代器(自己用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后面的东西是给对象传的值,多个值放在一个元组中

猜你喜欢

转载自www.cnblogs.com/mmyy-blog/p/9298076.html
今日推荐