2014-09-21 42 views
2

我需要創建包含另一個具有8個元素的列表的列表1。然後將這些附加到最後一個元素被更改的第二個列表中。 當我嘗試更改最後一個元素時,我有點困惑,它改變了這兩個列表的最後一個元素。將元素指定給2D列表也會更改另一個列表

任何幫助將非常感激:

from random import random 

list1 = [] 
list2 = [] 

for x in xrange(10): 

    a, b, c, d, e, f, g = [random() for i in xrange(7)] 

    list1.append([x, a, b, c, d, e, f, g]) 

for y in xrange(len(list1)): 

    list2.append(list1[y]) 
    print "Index: ", y, "\tlist1: ", list1[y][7] 
    print "Index: ", y, "\tlist2: ", list2[y][7] 

    list2[y][7] = "Value for list2 only" 

    print "Index: ", y, "\tlist1: ", list1[y][7] 
    print "Index: ", y, "\tlist2: ", list2[y][7] 
+0

其他相關問題:http://stackoverflow.com/questions/16774913/why -is-list-changing-with-no-reason,http://stackoverflow.com/questions/12237342/changing-an-item-in-a-list-of-lists,http://stackoverflow.com/questions/11993878/Python的 - 爲什麼 - 不,我的列表 - 變化 - 當-IM-未實際變化 - 它。 – Veedrac 2014-09-21 06:56:30

回答

1

替換:

list2.append(list1[y]) 

有:

list2.append(list1[y][:]) 

與原代碼的問題是,Python是不附加數據從list1[y]list2的末尾。相反,python會附加一個指向list1[y]的指針。在任何一個地方更改數據,並且由於它是相同的數據,所以更改顯示在兩個地方。

解決方案是使用list1[y][:],它告訴python製作數據的副本。

你可以看到更多的只是這一效果列表清單:

>>> a = [0, 1, 2, 3, 4, 5, 6, 7] 
>>> b = a 
>>> b[0] = 99 
>>> a 
[99, 1, 2, 3, 4, 5, 6, 7] 

相反:

>>> a = [0, 1, 2, 3, 4, 5, 6, 7] 
>>> b = a[:] 
>>> b[0] = 99 
>>> a 
[0, 1, 2, 3, 4, 5, 6, 7] 
相關問題