【发布时间】:2020-11-10 16:11:14
【问题描述】:
我运行了这个脚本,但我不明白列表反转是如何工作的。
class Queue:
def __init__(self):
self._push_stack = list()
self._pop_stack = list()
def push(self, x):
self._push_stack.append(x)
self._pop_stack.append(x)
self._pop_stack.reverse()
print(self._push_stack, self._pop_stack) # debugging
def pop(self):
if len(self._pop_stack) == 0:
raise IndexError("pop from an empty queue")
else:
self._push_stack.pop()
return self._pop_stack.pop()
queue = Queue()
queue.push(3)
queue.push(5)
queue.push(7)
queue.push(9)
print(queue.pop())
print(queue.pop())
print(queue.pop())
print(queue.pop())
这个脚本的输出是:
[3] [3]
[3, 5] [5, 3]
[3, 5, 7] [7, 3, 5]
[3, 5, 7, 9] [9, 5, 3, 7]
7
3
5
9
我不明白为什么[3, 5, 7] 颠倒时是[7, 3, 5] 而不是[7, 5, 3];为什么[3, 5, 7, 9],在颠倒时是[9, 5, 3, 7],而不是[9, 7, 5, 3]。
PS 请忽略脚本的其他缺点。
【问题讨论】:
-
在添加每个元素后,您正在颠倒
pop_stack的顺序 - 这会导致一些非常奇怪的元素顺序 -
你试过调试代码吗?
-
我不知道你想要什么解释,你奇怪的代码和调试输出还没有演示。你不断颠倒
self._pop_stack的顺序,所以它以一个奇怪的顺序结束。 -
忽略脚本的其他缺点会忽略此行为的原因..
-
How to debug small programs. | What is a debugger and how can it help me diagnose problems? 在第二次迭代之后,您拥有
push: [3, 5] pop: [5, 3]。然后将 7 附加到每个列表,因此您有push: [3, 5, 7] pop: [5, 3, 7]。然后你反转pop,所以你有push: [3, 5, 7] pop: [7, 3, 5]。您的调试输出已经告诉您这一点。