簡體   English   中英

在while循環內進行的變量更改未反映在Python 3的循環外

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

我在while循環外定義了一個變量(名為root ),並在while循環內對其進行了更改,但這些更改未在while循環外反映出來。 我已將root變量初始化為值為OLD_VALUETreeNode ,然后在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的新值。 您只需將根值彈出到循環中即可。 這就是為什么它在循環內外都顯示相同的值的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM