day14-生成器進階

1.send()

'''
def generator():
    print(123)
    yield 1
    print(456)
    yield 2
    print(789)

g = generator()
ret = g.__next__()
print(ret)
ret = g.send(None) # send的效果和_next_同樣
print(ret)
'''

def generator():
    print(123)
    content = yield 1
    print(content)
    print(456)
    yield 2

g = generator()
ret = g.__next__()
print(ret)
ret = g.send('hello') # send的效果和_next_同樣
print(ret)
# send和_next_效果同樣,他在打印出第二個yield以前,還將send裏面的hello傳給content,因此也會打印出hello。
#result:
# 123
# 1
# hello
# 456
# 2

使用send注意事項:spa

(1)第一次使用生成器,必須用_next_獲取值。code

(2)最後一個yield,不能接收外部的值。blog

2.計算移動平均值

def average():
    avg = 0
    sum = 0
    count = 0
    while True:
        rcp = yield avg
        sum += rcp
        count += 1
        avg = sum / count
avg_g = average()
avg_g.__next__()
Avg = avg_g.send(10)
print(Avg)
Avg = avg_g.send(20)
print(Avg)

3.yield from 變量

def generator():
    a = '12345'
    b = 'abcde'
    for i in a: # 方法一
        yield i
    yield from b # 方法二
g = generator()
for i in g:
    print(i)
相關文章
相關標籤/搜索