Python 3.x 如何证明这种python数组工作行为的合理性?
第二个push(6)如何维护堆栈数组并不是第二个push()方法应该创建一个新数组,它如何在push()的多个方法调用之间维护数组 全文如下:Python 3.x 如何证明这种python数组工作行为的合理性?,python-3.x,Python 3.x,第二个push(6)如何维护堆栈数组并不是第二个push()方法应该创建一个新数组,它如何在push()的多个方法调用之间维护数组 全文如下: 全文如下:这是否回答了您的问题?这回答了你的问题吗?明白了,还有这个,我还了解到python中的函数是一个第一类对象,因此,当第一次执行def push时,在该函数的作用域中分配和维护数组堆栈,随后调用该函数将在该函数的作用域中使用相同的数组。如果其非原始的,原始的观察不到相同的行为是可以理解的。明白了,还有这个,我还了解到python中的函数是一个第一
全文如下:这是否回答了您的问题?这回答了你的问题吗?明白了,还有这个,我还了解到python中的函数是一个第一类对象,因此,当第一次执行def push时,在该函数的作用域中分配和维护数组堆栈,随后调用该函数将在该函数的作用域中使用相同的数组。如果其非原始的,原始的观察不到相同的行为是可以理解的。明白了,还有这个,我还了解到python中的函数是一个第一类对象,因此,当第一次执行def push时,在该函数的作用域中分配和维护数组堆栈,随后调用该函数将在该函数的作用域中使用相同的数组。如果其非原语,原语的相同行为是无法观察到的,这是可以理解的。
def push(item,stack=[]):
#print('stack',stack)
stack.append(item)
return stack
if __name__== '__main__':
print(push(5))
print(push(6))
print(push(7))
stck = push(58)
print(stck.pop())
print(stck.pop())
print(push(9))
Answer:
[5]
[5, 6]
[5, 6, 7]
58
7
[5, 6, 9]
Answer:
[5] -> You use *stack = []* variable from the push() function as location to store
[5, 6] -> Same
[5, 6, 7] -> Same
58 -> It creates inside new variable *stck* a copy for the *stack = []* variable
7 -> It removes from the *stack = []*
[5, 6, 9] -> It addes to the *stack = []* the new element
The *stck* variable is just a reference to the *stack* variable, changing that one, it changes the stck as well.
Is not recommended to use a list as a function parameter.