Skip to main content
 首页 » 编程设计

python之将元素分配给二维列表也会更改另一个列表

2025年05月04日9haluo1

<分区>

我需要创建包含另一组具有 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]