Python中yield和yield from有什么区别?协程如何工作?

进阶Python

答题要点

# 生成器(yield)
def number_generator():
    yield 1
    yield 2
    yield 3

# yield from 委托给子生成器
def combined_generator():
    yield from number_generator()
    yield from [4, 5, 6]

# 双向通信(协程)
def coroutine():
    total = 0
    while True:
        value = yield total
        if value is None:
            break
        total += value

c = coroutine()
next(c)         # 启动
c.send(10)      # 发送值,返回20
c.send(20)      # 返回30

# 子生成器委托
def accumulator():
    total = 0
    while True:
        value = yield
        if value is None:
            return total
        total += value

def grouper():
    while True:
        total = yield from accumulator()
        print(f"Total: {total}")

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题