这是我的代码,用于将数据从旧堆栈复制到新堆栈,然后将它们加入队列
for word in dictionary:
if len(word) == len(lastWord): #Make sure same len
if (oneLetterDiff(word, dequeuedStack.peek())) == True and (word in dequeuedStack._data) == False: #One letter difference
s = MyStack()
print 'before %s' % dequeuedStack._data
s.copyFrom(dequeuedStack) #Copy stack over
s.push(word) #Add new word
print 'after %s' % s._data
q.enqueue(s) #Enqueue the stack
print 'after copying %s' % dequeuedStack._data
print word
这是复制列表的代码
def copyFrom(self, aStack):
self._data = aStack._data
这是将它附加到队列中
def enqueue(self, value):
self._data.append(value)
但是,dequeuedStack._data
被更改了,我没有调用任何方法来修改它
这是一个输出示例
['stone', 'atone']
before ['stone', 'atone']
after ['stone', 'atone', 'alone']
after copying ['stone', 'atone', 'alone']
alone
before ['stone', 'atone', 'alone']
after ['stone', 'atone', 'alone', 'clone']
after copying ['stone', 'atone', 'alone', 'clone']
clone
将复制到列表的方法更改为
self._data = aStack._data[:]
,它可以工作Python中的字典是引用。这意味着在执行
self._data = aStack._data
操作时,实际上是在使两个字典具有相同的引用,而不是实际地创建一个新字典并将值复制到它。你知道吗要进行深度复制,请尝试以下操作:
相关问题 更多 >
编程相关推荐