[英]Change in variable made inside of a while loop is not reflected outside of the loop in Python 3
I have a variable (named root
) defined outside the while loop and am making changes to it inside the while loop but those changes are not being reflected outside the while loop. 我在while循环外定义了一个变量(名为
root
),并在while循环内对其进行了更改,但这些更改未在while循环外反映出来。 I have initialized my root
variable as a TreeNode
with value OLD_VALUE
and then changes its value to NEW_VALUE
inside the while loop. 我已将
root
变量初始化为值为OLD_VALUE
的TreeNode
,然后在while循环内将其值更改为NEW_VALUE
。 After printing the value of root
outside the loop, it is still showing the original value ie OLD_VALUE
. 在循环外打印
root
的值后,它仍显示原始值,即OLD_VALUE
。 So, the pseudo-code is as follows (I can share the actual code if needed): 因此,伪代码如下(如果需要,我可以共享实际代码):
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
Its because you dont change the value of root in the while loop. 这是因为您没有在while循环中更改root的值。 you have all_items changed and stack but not root.
您更改了all_items并堆栈但没有root用户。 Thats why there is no change, because you dont assign any kind of change through this variable
这就是为什么没有更改的原因,因为您没有通过此变量分配任何更改
You are just assign the value & push into the stack outside the loop. 您只需分配值并在循环外将其压入堆栈。 In while loop, you are not performing any operation to set the new value of the variable
root
. 在while循环中,您没有执行任何操作来设置变量
root
的新值。 You just pop the root value inside the loop . 您只需将根值弹出到循环中即可。 Thats why it show the same value inside & outside the loop.
这就是为什么它在循环内外都显示相同的值的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.