Python 递归未返回值

3 投票
5 回答
2045 浏览
提问于 2025-04-16 17:38

在这段代码中,x 似乎没有在递归中更新。难道不应该在 a(y) 中调用 b(c) 的时候,x 也跟着更新吗?虽然在 b(c) 中 x 有更新,但它并没有返回到

global nested
def extract(nested,depth):
    y = depth[0]
    depth = depth[1:]
    extract = nested[y]
    newlist(extract)
    return depth
def newlist(x):
    nested = x
    return nested
def recursiveRef(nested,depth):
    """Return element from nested list
    list ->int
    """
    if len(depth) == 0:
        return nested
    else:
        return recursiveRef(nested,extract(nested,depth))

5 个回答

1

你的代码看起来有点可疑。当你觉得需要一个全局变量的时候,通常你其实想要的是一个类。可以考虑把你的函数放进一个类里,然后用 self.x 来代替 x。

另外,"global" 这个词不应该写在你程序的最上面。相反,你需要在每个会修改全局变量的函数里写它,但那些只读取全局变量的函数就不需要写。

def newlist(x):
    global nested
    nested = x
    return nested
1

我不是Python高手,但我觉得问题出在x是递归函数内部的局部变量。你在b(c)里改变了另一个全局的x。如果我说错了,请纠正我。

3

你是想这样做吗?

def recursiveRef(nested,depth):
    """Return element from nested list
    list ->int
    """
    if len(depth) == 0:
        return nested
    else:
        return recursiveRef(nested[depth[0]],depth[1:])

print recursiveRef([[1,2,3],[4,[5,6],7]],[1])
print recursiveRef([[1,2,3],[4,[5,6],7]],[1,1])
print recursiveRef([[1,2,3],[4,[5,6],7]],[1,1,1])

输出结果

[4, [5, 6], 7]
[5, 6]
6

撰写回答