我有一个名为self.nodePathList的列表,其中包含[782,455,231]。然后,我将其放入另一个列表变量:self.sortedNodePath = self.nodePathList。这两个列表现在包含相同的内容。我对self.sortedNodePath进行排序。但是,它们都被排序了。我反复检查了代码,但没有出现任何拼写错误或使用错误的名称。如果您要使用下面的代码
self.sortedNodePath = self.nodePathList
#######sorting
for passnum in range(len(self.sortedNodePath)-1,0,-1):
for i in range(passnum):
if self.sortedNodePath[i]>self.sortedNodePath[i+1]:
self.temp = self.sortedNodePath[i]
self.sortedNodePath[i] = self.sortedNodePath[i+1]
self.sortedNodePath[i+1] = self.temp
#######END OF SORTING
在你的榜样,self.sortedNodePath
并且self.nodePathList
都指向同一个对象。当您对该对象进行排序时,两个变量仍指向该对象。
您需要使用以下方法创建一个新对象:
self.sortedNodePath = list(self.nodePathList)
举个例子:
foo = ['test', 'foo']
bar = foo
print id(foo)
>>> 23367192
print id(bar)
>>> 23367192 # You can see both foo and bar have the same object ID
bar = list(foo)
print id(bar)
>>> 23387392 # Now using list(), bar has a separate object ID from foo
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句