【问题标题】:How to yield all values returned by nested iterator?如何产生嵌套迭代器返回的所有值?
【发布时间】:2014-07-30 08:14:24
【问题描述】:

我为 JSON 创建了一个简单的深度树扫描(只有列表和值,没有对象):

def depth(x):
    for e in x:
        if type(e) == list:
            for s in depth(e):
                yield s
        else:
            yield(e)

建筑

for s in depth(e):
    yield s

工作正常,但我不喜欢它。

是否有任何不错的方法来生成调用函数所生成的所有内容,而无需循环?

【问题讨论】:

  • 我会避免特殊情况 - 总是处理一个序列或从不这样做 - 如果可能的话。

标签: python recursion tree yield


【解决方案1】:

在 Python 3.3 或更高版本中,您可以使用 yield from depth(e)。在早期版本的 Python 中,您必须像以前那样写出嵌套循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多