2014-09-21 55 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] 
相关问题