在 Python 3 中,在 while 循环内部所做的变量更改不会反映在循环外部

Change in variable made inside of a while loop is not reflected outside of the loop in Python 3

我在 while 循环外定义了一个变量(名为 root),我正在 while 循环内对其进行更改,但这些更改不会反映在 while 循环外。我已将我的 root 变量初始化为 TreeNode,值为 OLD_VALUE,然后在 while 循环内将其值更改为 NEW_VALUE。在循环外打印 root 的值后,它仍然显示原始值,即 OLD_VALUE。所以,伪代码如下(如果需要我可以分享实际代码):

class TreeNode: #Defines nodes of a binary tree
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

class Solution(object): #this is my main class where I have a problem
    def buildTree(self, pre, ino):
        ##some code
        root = TreeNode(OLD_VALUE) #This is the variable in question
        stack = [] #Basically I am sending the variable 'root' through this stack
        stack.append([item1, item2, item3, item4, root])
        while(stack):
            all_items = stack.pop()
            ##some code
            all_items[4] = TreeNode(NEW_VALUE) #Note, all_items[4] is root actually
            ##some code
            (#val1, val2, val3, val4 are some computed values)
            stack.append([val1, val2, val3, val4, all_items[4].right]) #Note, all_items[4] is root
            stack.append([val1, val2, val3, val4, all_items[4].left]) #Note, all_items[4] is root
        print(root.val)
        #It prints OLD_VALUE instead of NEW_VALUE

这是因为你没有在while循环中改变root的值。您已更改 all_items 并堆栈但不是 root。这就是为什么没有变化,因为你没有通过这个变量分配任何类型的变化

您只是在循环外分配值并压入堆栈。 在 while 循环中,您没有执行任何操作来设置变量 root 的新值。您只需在循环中弹出根值。这就是为什么它在循环内外显示相同的值。