Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python堆栈!特别是stack.push(stack.pop))_Python_Stack - Fatal编程技术网

Python堆栈!特别是stack.push(stack.pop))

Python堆栈!特别是stack.push(stack.pop)),python,stack,Python,Stack,我在理解stack.push(stack.pop())在此代码中的作用时遇到一些问题 stack = Stack() stack.push('1') stack.push('2') stack.push('3') x = stack.pop() y = stack.pop() z = stack.pop() stack.push(y) stack.push(y) stack.push('2') while not stack.is_empty(): print(stack.pop(),

我在理解stack.push(stack.pop())在此代码中的作用时遇到一些问题

stack = Stack()
stack.push('1')
stack.push('2')
stack.push('3')
x = stack.pop()
y = stack.pop()
z = stack.pop()
stack.push(y)
stack.push(y)
stack.push('2')
while not stack.is_empty():
    print(stack.pop(), end='')

我知道堆栈上应该有3个项目,但我不知道它们是什么以及它们最后将如何打印?如果能帮我解决这个问题,我将不胜感激!谢谢

堆栈
是一个类似于一堆盘子的物体。当您
按下
时,您将向堆栈顶部添加一个板,当您
弹出
时,您将从顶部移除一个板。你不会想从底部取回一个盘子,这既昂贵又不必要

在本例中,
stack.push(stack.pop())
不执行任何操作。它将
从堆栈顶部弹出
项目,并
将其再次推到顶部。在
while
循环中,将
项目从堆栈中弹出,直到没有更多项目为止
pop
返回已删除的项目,以便打印

示例:

# declare empty stack
stack = Stack()

# Now the stack has one item in it, a string called "hello"
stack.push("hello")

# x is now a string "hello", and we have removed it from
# the stack. stack is now empty
x = stack.pop()

# stack now has x in it
stack.push(x)

# we add a string "world" to the top of the stack
stack.push("world")

# x is now the value of the top of the stack, "world"
# The stack also only has "hello" in it, since "world" was
# removed
x = stack.pop()

@hotpockets,还要注意,这意味着如果你按1,2,然后按3,然后按三次,你会得到3,2,1(按相反的顺序),现在堆栈是空的。这称为后进先出结构(后进先出)