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]
>>>
感謝解釋。 – dansalmo 2012-04-25 05:56:59
...或使用'copy.copy()':-)。 – Fenikso 2012-04-25 07:59:30