Python_生成器函数进阶_39

def generator():
print(123)
content = yield 1 #content接收的是send传的值
print('=======',content)
print(456)
arg = yield 2
print('nihao')
''''''
yield g = generator()
ret = g.__next__() #
print('***',ret) # *** 1
ret = g.send('hello') #send的效果和next一样
# print('***',ret)
g.__next__() '''

123
*** 1
======= hello
456
nihao

'''
def generator():
print(123)
yield 1
print('=======')
print(456)
arg = yield 2
print('nihao')
''''''
yield g = generator()
ret = g.__next__() #
print('***',ret) # *** 1
ret = g.send(None) #send的效果和next一样
# print('***',ret)
g.__next__() '''
123
*** 1
=======
456
nihao
'''
def generator():
print(123)
content = yield 1
print('=======',content)
print(456)
arg = yield 2
print('nihao')
''''''
yield g = generator()
ret = g.__next__() #
print('***',ret) # *** 1
ret = g.__next__() #send的效果和next一样
print('***',ret)
g.__next__()
print('***',ret) '''

*** 1
======= None
456
*** 2
nihao
*** 2

'''

#send 获取下一个值的效果和next基本一致
#只是在获取下一个值的时候,给上一yield的位置传递一个数据
#使用send的注意事项
# 第一次使用生成器的时候 是用next获取下一个值
# 最后一个yield不能接受外部的值

# 获取移动平均值

# 10 20 30 10
# 10 15 20 17.5
#avg = sum/count def average():
sum = 0
count = 0
avg = 0
while True:
num = yield avg
sum += num #
count += 1 #
avg = sum/count avg_g = average()
avg_g.__next__()
avg1 = avg_g.send(10)
avg1 = avg_g.send(20)
print(avg1)
#预激生成器的装饰器
def init(func): #装饰器
def inner(*args,**kwargs):
g = func(*args,**kwargs) #g = average()
g.__next__()
return g
return inner @init
def average():
sum = 0
count = 0
avg = 0
while True:
num = yield avg
sum += num #
count += 1 #
avg = sum/count avg_g = average() #===> inner
ret = avg_g.send(10)
print(ret)
ret = avg_g.send(20)
print(ret)
import os

def init(func):
def wrapper(*args,**kwargs):
g=func(*args,**kwargs)
next(g)
return g
return wrapper @init
def list_files(target):
while 1:
dir_to_search=yield
for top_dir,dir,files in os.walk(dir_to_search):
for file in files:
target.send(os.path.join(top_dir,file))
@init
def opener(target):
while 1:
file=yield
fn=open(file)
target.send((file,fn))
@init
def cat(target):
while 1:
file,fn=yield
for line in fn:
target.send((file,line)) @init
def grep(pattern,target):
while 1:
file,line=yield
if pattern in line:
target.send(file)
@init
def printer():
while 1:
file=yield
if file:
print(file) g=list_files(opener(cat(grep('python',printer())))) g.send('/test1') 协程应用:grep -rl /dir tail&grep
#python 3
def generator():
a = 'abcde'
b = ''
for i in a:
yield i
for i in b:
yield i def generator():
a = 'abcde'
b = ''
yield from a
yield from b g = generator()
for i in g:
print(i) # send
# send的作用范围和next一模一样
# 第一次不能用send
# 函数中的最后一个yield不能接受新的值 # 计算移动平均值的例子
# 预激生成器的装饰器的例子
# yield from

Python_生成器函数进阶_39

Eva_J

https://www.cnblogs.com/Eva-J/p/7277026.html

上一篇:如何合并多个PPT


下一篇:ZIP打包解包