这是一个奇怪的。除非我在做一些愚蠢的事情。我有以下代码:一个变量是另一个变量也在改变原来的
gps_markers = [ ['Example text', 34.4563,-118.1241], [34.5235,-118.1245], [34.6432,-118.1554] ]
new_gps = gps_markers
def make_points(coords):
if(coords):
# Firstly we don't want the hover text.
for x in range(0, len(coords)):
if(len(coords[x]) == 3):
coords[x].pop(0)
new_list = [{'lat': d[0], 'lng': d[1]} for d in coords]
# Return the new list after the list comprehension.
return new_list
print '\nbefore newgps ->', gps_markers
new_gps = make_points(new_gps)
print '\nafter newgps ->', gps_markers
然后运行脚本,我从打印行获得以下输出。
before newgps -> [['Example text', 34.4563, -118.1241], [34.5235, -118.1245], [34.6432, -118.1554]]
after newgps -> [[34.4563, -118.1241], [34.5235, -118.1245], [34.6432, -118.1554]]
现在为什么它对我没有意义。第一个变量gps_markers
不应该在这个脚本的任何位置生效,对吧?我制作gps_markers
的副本new_gps
。然后通过我的make_points
方法运行new_gps
。这将影响该变量。但它也影响gps_markers
?不知道是否我只是一直盯着这个太长时间,或者是否有我失踪的东西。感觉就像两个一样。
参见[这里](http://stackoverflow.com/questions/17707742/changing-a-value-in-one-list-changes-the-values-in-another-list-with-a-different ) – roganjosh
在第二行中应该是'new_gps = gps_markers [:]'。这将创建第一个列表的副本。 – Nf4r
'a = b'不会生成b的新副本。 a和b是SAME对象的不同名称。 –