Python 使用和不使用全局变量的递归

Python recursion with and without using global variable

到目前为止我的代码:

import statistics

def nested_median(nest, templist=[]):
    
    if not nest:
        pass
    
    elif isinstance (nest[0], list):
        nested_median(nest[0]), nested_median(nest[1:])

    elif isinstance (nest[0], int):
        templist.append(nest[0])
        nested_median(nest[1:])
        return statistics.median(templist)

    else:
        nested_median(nest[1:])

我正在尝试编写一个程序,它将任意嵌套列表作为输入,returns 列表 and/or 子列表中所有整数的中值,同时忽略所有其他元素。例如:

nested_median([3,2,"Hello",[1,5],("Hello", "world"),5,9.3]) == 3

我在上面提出了一个使用全局变量的解决方案,但这只适用于一个函数调用,因为 templist 没有得到 cleared.I 有两个问题:

  1. 我将如何清除函数调用之间的全局变量?

  2. 如何在不使用全局变量的情况下实现它?

您描述为“变量未清除”的问题是“可变默认参数”问题。许多博客和教程都是关于它的。在这里看到:"Least Astonishment" and the Mutable Default Argument.


下面是一个递归生成器,用于展平任意嵌套列表,稍微修改为 return 仅整数。

def ifl(x):
    if isinstance(x, list):  # to flatten tuples as well: isinstance(x, (list, tuple))
        for item in x:
            yield from ifl(item)
    elif isinstance(x, int):
        yield x
    # else: ignore x

test = [3,2,"Hello",[1,5],("Hello", "world"),5,9.3]
ints = list(ifl(test))  # [3, 2, 1, 5, 5]
# ... compute median