【问题标题】:Python stack contents are overwritten when passed to a function传递给函数时,Python 堆栈内容被覆盖
【发布时间】:2014-11-29 00:16:34
【问题描述】:

我编写了一个快速的 Python 函数来反转堆栈的内容。

def ReverseStack(input_stack):
    oldStack = input_stack
    newStack = Stack()

    while not oldStack.isEmpty():
        item = oldStack.pop()
        newStack.push(item)
    return newStack

s = Stack()
s.push('hello')
s.push('world')
s.push('I')
s.push('live')
s.push('underwater')

new = ReverseStack(s)

print "\nOriginal stack..."
while not s.isEmpty():
    print s.pop()

print "\nNew stack..."
while not new.isEmpty():
    print new.pop()

但是,当我打印每个堆栈的内容(原始堆栈和反向堆栈)时,看起来好像原始堆栈的所有内容都已通过 pop 方法删除。这让我很困惑,因为我将它作为参数传递给了一个创建临时堆栈以将内容弹出的函数。我原以为这样会原封不动。

我的问题是为什么会发生这种情况,纠正它的最佳方法是什么?谢谢!

【问题讨论】:

    标签: python function python-2.7 stack


    【解决方案1】:

    线

    oldStack = input_stack
    

    使 oldStack 成为对同一对象的引用,而不是副本。你需要使用

    import copy
    

    复制任意对象。

    可能纠正它的最佳方法是遍历堆栈,而不是从堆栈中弹出项目。

    可能有用的参考:http://www.python-course.eu/deep_copy.php

    【讨论】:

    • 很好,我知道它必须是这样的,我只是不知道如何解决它。谢谢!
    【解决方案2】:

    你将一个可变对象传递给 ReverseStack 并且 ReverseStack 改变了它。 Python 在传递给函数时不会复制对象(这会很昂贵),因此您要么必须自己复制它,要么编写不修改传入内容的函数......除非这是函数的重点.

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 2023-03-21
      • 2014-04-06
      相关资源
      最近更新 更多