【问题标题】:recursive generator not working [duplicate]递归生成器不工作[重复]
【发布时间】:2018-08-10 02:02:48
【问题描述】:

我正在使用他的代码来扁平化嵌套元组:

def get_tuple_leaves(t, out=[]):
    for i in t:
        if isinstance(i, str):
            yield i
        else:
            get_tuple_leaves(i, out)

想法是得到一个输入如(('a', 'b'), 'c') 转为('a', 'b', 'c')

但由于某种原因,递归调用永远不会被执行,并且输出是 ('c')

【问题讨论】:

  • out 变量的用途是什么?你没有用它做任何事情。
  • 另外,假设您的 out 的默认值实际上是在做某事,如果您不了解它的语义,您应该小心使用可变默认参数

标签: python recursion tuples


【解决方案1】:

你没有返回,或者更确切地说,是从你的递归调用中让步。试试:

def get_tuple_leaves(t, out=[]):
    for i in t:
        if isinstance(i, str):
            yield i
        else:
            yield from get_tuple_leaves(i, out)

print(list(get_tuple_leaves((('a', 'b'), 'c'))))

导致:

['a', 'b', 'c']

【讨论】:

    猜你喜欢
    • 2016-10-05
    • 1970-01-01
    • 2016-04-19
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 2019-08-25
    • 2021-05-22
    相关资源
    最近更新 更多