Python生成器从另一个生成器调用中产生一切 [英] Python generator to yield everything from another generator call

查看:217
本文介绍了Python生成器从另一个生成器调用中产生一切的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python生成器,可以调用它自己来获取更多要生成的元素.看起来像这样:

I have a Python generator that can call itself to get more elements to yield. It looks like this:

def gen(list):
    # ...
    if list:
        for x in gen(list[1:]):
            yield x

我的问题是关于最后两行:有没有更简洁的方式来表达这一点?我希望有这样的东西(理解这不是按原样的有效Python):

My question is about the last two lines: is there a more concise way to express this? I am hoping for something like this (understanding this isn't valid Python as-is):

def gen(list):
    # ...
    if list:
        yield each in gen(list[1:])

推荐答案

Python 3.3

Python 3.3 added the yield from keyword. Here's a comparison between what you currently have and code using the new keyword:

yield_from_test.py:

def gen_for(a_list):
    if a_list:
        yield a_list[0]
        for x in gen_for(a_list[1:]):
            yield x

def gen_yield(a_list):
    if a_list:
        yield a_list[0]
        yield from gen_yield(a_list[1:])

if __name__ == '__main__':
    assert list(gen_for([1,2,3])) == list(gen_yield([1,2,3]))
    print(list(gen_yield([1,2,3])))

» python3 yield_from_test.py [1, 2, 3]

» python3 yield_from_test.py [1, 2, 3]

这篇关于Python生成器从另一个生成器调用中产生一切的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆