Python:展平包含另一个生成器的生成器的函数 [英] Python: Function to flatten generator containing another generator

查看:65
本文介绍了Python:展平包含另一个生成器的生成器的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何编写python函数,该函数可以使生成器变平,从而生成另一个生成器或可迭代项(也可以无限生成另一个生成器/可迭代项……).

I would like to know how to write python function which can flatten generator which yields another generators or iteables (which can also yield another generators/iterables ... possibly infinitely).

以下是示例:

gen(gen(1,2,3), gen(4,5,6), [7,8,9], [gen(10,11,12), gen(13,14,15)])

注意:gen-表示生成器对象,gen之后的括号之间的内容是将生成生成器gen的数据.

note: gen - means generator object, content between parentheses after gen is data that will generator gen yield.

展平"后的预期结果: gen(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)

The expected result after "flattening": gen(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)

flatten函数也必须返回生成器! (否则,生成器的先前用法将毫无意义).

It is necessary for the flatten function to return generator too! (because otherwise, the preceeding usage of generators would be meaningless).

请注意,我正在使用python 3.

Just to note, I am using python 3.

谢谢!

推荐答案

最简单的方法是递归展平函数.假设您想进入除字符串之外的所有可迭代对象,可以执行以下操作:

The easiest way is a recursive flattening function. Assuming you want to descend into every iterable except for strings, you could do this:

def flatten(it):
    for x in it:
        if (isinstance(x, collections.Iterable) and
            not isinstance(x, str)):
            for y in flatten(x):
                yield y
        else:
            yield x

从Python 3.3开始,您还可以编写

Starting from Python 3.3, you can also write

def flatten(it):
    for x in it:
        if (isinstance(x, collections.Iterable) and
            not isinstance(x, str)):
            yield from flatten(x)
        else:
            yield x

这篇关于Python:展平包含另一个生成器的生成器的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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