为什么我不能修改作为函数内部参数传递的列表?
Why can't I modify a list passed as an argument inside a function?
这是上下文。我有一个这样定义的树结构:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
我正在尝试使用函数 find_x
递归迭代树。该函数依赖于作为参数传递的列表 to_do
。
x = defaultdict(lambda:[])
def find_x (x, to_do):
next_to_do = []
for node, n in to_do:
x[n].append(node.val)
if node.left:
next_to_do.append((node.left, n - 1))
if node.right:
next_to_do.append((node.right, n + 1))
to_do = next_to_do
to_do = [(root, 0)]
while to_do:
find_x(x, to_do)
当我 运行 我的函数时,我看到 to_do
没有更新。我知道如果我想更新 to_do
,我需要更改 find_x
并将最后一行替换为 return next_to_do
并且我需要更改 while
循环的内部进入 to_do = find_x(x, to_do)
.
我的问题是这样的。由于我的列表 to_do
是一个可变对象,并且它是在函数 find_x
之外定义的,因此函数 find_x
应该能够修改它。为什么不是呢?
感谢您的帮助!
您正在函数 find_x
中创建一个新变量 to_do
,您可以使用:
to_do[:] = next_to_do
这是上下文。我有一个这样定义的树结构:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
我正在尝试使用函数 find_x
递归迭代树。该函数依赖于作为参数传递的列表 to_do
。
x = defaultdict(lambda:[])
def find_x (x, to_do):
next_to_do = []
for node, n in to_do:
x[n].append(node.val)
if node.left:
next_to_do.append((node.left, n - 1))
if node.right:
next_to_do.append((node.right, n + 1))
to_do = next_to_do
to_do = [(root, 0)]
while to_do:
find_x(x, to_do)
当我 运行 我的函数时,我看到 to_do
没有更新。我知道如果我想更新 to_do
,我需要更改 find_x
并将最后一行替换为 return next_to_do
并且我需要更改 while
循环的内部进入 to_do = find_x(x, to_do)
.
我的问题是这样的。由于我的列表 to_do
是一个可变对象,并且它是在函数 find_x
之外定义的,因此函数 find_x
应该能够修改它。为什么不是呢?
感谢您的帮助!
您正在函数 find_x
中创建一个新变量 to_do
,您可以使用:
to_do[:] = next_to_do