# yield-yield from

**1.入门级讲解**

yield本身返回的是一个iter，好处：我想要\[0-无穷]的数组，你难道到返回这么多数吗？返回i=0;;i++就好了

有yield的函数以当前`yield为分界线`，每次到这停止，下次来执行下半部分

```python
def pre():
    yield 1
    yield 2
    yield 3
    yield 4


abc = pre()
print(next(abc)) # 迭代1次
print(list(abc)) #一直迭代直到完
```

```python
# 字符串
astr = 'ABC'
# 列表
alist = [1, 2, 3]
# 字典
adict = {"name": "wangbm", "age": 18}
# 生成器
agen = list((i for i in range(4, 8)))


def gen_yield(*args, **kw):
    '''
    :desc yield
    :param args:
    :param kw:
    :return:
    '''
    for item in args:
        for i in item:
            yield i


def gen_yield_from(*args, **kw):
    '''
    :desc yield from
    :param args:
    :param kw:
    :return:
    '''
    # 细微差别看到了吗？yield from能迭代集合里面的数据
    for item in args:
        yield from item


new_list = gen_yield(astr, alist, adict, agen)
new_list_2 = gen_yield_from(astr, alist, adict, agen)
print(list(new_list))
print(list(new_list_2))

'''
['A', 'B', 'C', 1, 2, 3, 'name', 'age', 4, 5, 6, 7]
['A', 'B', 'C', 1, 2, 3, 'name', 'age', 4, 5, 6, 7]
'''



# ------------例子2，执行顺序详细打印------------
def yield_test(n):
    for i in range(n):
        yield call(i)
        print("range,i=", i)
        # 做一些其它的事情
    print("do something.")
    print("end.")

def call(i):
    print('call,i=', i)
    return i * 2

# 使用for循环
for i in yield_test(5):
    print('print,i=', i)
    print('-' * 20)
'''
call,i= 0
print,i= 0
--------------------
range,i= 0
call,i= 1
print,i= 2
--------------------
range,i= 1
call,i= 2
print,i= 4
--------------------
range,i= 2
call,i= 3
print,i= 6
--------------------
range,i= 3
call,i= 4
print,i= 8
--------------------
range,i= 4
do something.
end.
'''
```

2.生成器

```python
# 子生成器
def average_gen():
    total = 0
    count = 0
    average = 0
    while True:
        new_num = yield average
        count += 1
        total += new_num
        average = total/count

# 委托生成器
def proxy_gen():
    while True:
        yield from average_gen()

# 调用send，向yield average中的average传值
def main():
    calc_average = proxy_gen()
    next(calc_average)            # 预激下生成器
    print(calc_average.send(10))  # 打印：10.0
    print(calc_average.send(20))  # 打印：15.0
    print(calc_average.send(30))  # 打印：20.0

main()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/python/yield.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
