Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将元素指定给二维列表也会更改另一个列表_Python_List_Python 2.7 - Fatal编程技术网

Python 将元素指定给二维列表也会更改另一个列表

Python 将元素指定给二维列表也会更改另一个列表,python,list,python-2.7,Python,List,Python 2.7,我需要创建一个包含另一组8个元素的列表的列表1。然后,这些元素被附加到第二个列表中,其中最后一个元素被更改。 我有点困惑,因为当我尝试更改最后一个元素时,它会更改两个列表的最后一个元素 在此方面的任何帮助都将不胜感激: 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.app

我需要创建一个包含另一组8个元素的列表的列表1。然后,这些元素被附加到第二个列表中,其中最后一个元素被更改。 我有点困惑,因为当我尝试更改最后一个元素时,它会更改两个列表的最后一个元素

在此方面的任何帮助都将不胜感激:

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]
替换:

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]
其他相关问题:。
>>> a = [0, 1, 2, 3, 4, 5, 6, 7]
>>> b = a[:]
>>> b[0] = 99
>>> a
[0, 1, 2, 3, 4, 5, 6, 7]