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注意事項:

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

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

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)

 

点赞

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *