对于python中的字典列表和其他类型的列表,切片复制的工作方式是否有所不同?

时间:2018-11-26 22:58:58

标签: python

使用切片复制列表,

 new_list = orig_list[:]
据我了解,

应该创建列表的新副本,并且对new_list所做的更改不应反映在orig_list中。但是,当我尝试使用字典列表进行相同操作时,其行为似乎有所不同,(orig_list有所更改)

示例代码:(1)是正常行为,(2)异常。在这两种情况下,我都尝试打印id,而它们确实是不同的引用

示例1:

data_train = ["ab","cd"]
cop = data_train[:]

print(id(data_train))
print(id(cop))

print("\ndata_train", data_train)
print("cop", cop)

cop[0]="blah"

print("\ndata_train", data_train) 
print("cop",cop)

结果

2002586717768
2002587528008

data_train ['ab', 'cd']
cop ['ab', 'cd']

data_train ['ab', 'cd']
cop ['blah', 'cd']

示例2:

data_train = [{1:'34'},{2:'48'}]
cop = data_train[:]

print(id(data_train))
print(id(cop))

print("\ndata_train", data_train)
print("cop", cop)

cop[0][1]="blah"

print("\ndata_train", data_train)
print("cop",cop)

结果

2002587517704
2002587528072

data_train [{1: '34'}, {2: '48'}]
cop [{1: '34'}, {2: '48'}]

data_train [{1: 'blah'}, {2: '48'}]
cop [{1: 'blah'}, {2: '48'}]

这里,在更改警察时,data_train也已更改。

为什么样本2显示此行为?

0 个答案:

没有答案