2012-04-25 32 views
0

我是python的新手,並且一直無法找到解釋我在下面看到的行爲的任何內容。我從方法中返回列表時發現了問題,並將其解壓縮到顯示問題的最簡單形式。我想出了一個解決方法,但想知道我在理解中缺少什麼,因爲我希望這兩個示例的行爲相同。Python列表受到返回列表的方法損壞

class MyCount: 
    """A simple count test to show return list problem""" 
    def __init__(self): 
     self.next = [0] 

    def count_good(self): 
     self.next[0] += 1 
     return [self.next[0]] 

    def count_bad(self): 
     self.next[0] += 1 
     return self.next # returning using this form corrupts the recieving list 


c=MyCount() 
result=4*[0] 
result[0]=c.count_good() 
result[1]=c.count_good() 
result[2]=c.count_bad() 
print result 
result[3]=c.count_bad() 
print result 


>>> c=MyCount() 
>>> result=4*[0] 
>>> result[0]=c.count_good() 
>>> result[1]=c.count_good() 
>>> result[2]=c.count_bad() 
>>> print result 
[[1], [2], [3], 0] 
>>> result[3]=c.count_bad() 
>>> print result 
[[1], [2], [4], [4]] <--- the return changed the previous item in the list 
>>> 
>>> c=MyCount() 
>>> result=4*[0] 
>>> c.count_good() 
[1] 
>>> c.count_good() 
[2] 
>>> c.count_bad() 
[3] 
>>> c.count_bad() <--- seems to work fine when not returning to a list 
[4] 
>>> 

回答

4

當你return self.next,你回到實際列表對象self.next指,不是副本參考。因此,從任何地方對原始列表對象所做的任何更改都會反映在引用該原始對象的所有位置。

爲了返回副本,你要麼做一個全切片:

return self.next[:] 

或使用list()功能:

return list(self.next) 
+0

感謝解釋。 – dansalmo 2012-04-25 05:56:59

+0

...或使用'copy.copy()':-)。 – Fenikso 2012-04-25 07:59:30