这是我凭直觉解决的一个问题,但并未真正理解根本问题。我什至不知道.copy()
方法。我只是使用IDE的自动完成功能来查找某些内容。我想知道您是否可以帮助我了解引用和内存地址的状况。这是按值引用问题还是其他问题?我是一个非常新的程序员,学习Python
作为我的第一语言。这是我所做工作的抽象:
dictionary_short = entries
dictionary_medium = dictionary_short
dictionary_medium.update(more_entries)
dictionary_long = dictionary_medium
dictionary_long.update(even_more_entries)
print(dictionary_short)
# *prints contents of long<!!!>dictionary*
我做到了:
dictionary_short = entries
dictionary_medium = dictionary_short.copy()
dictionary_medium.update(more_entries)
dictionary_long = dictionary_medium.copy()
dictionary_long.update(even_more_entries)
print(dictionary_short)
# *prints contents of short dictionary only*
答案 0 :(得分:0)
D={}
copy(...) method of builtins.dict instance
D.copy() -> a shallow copy of D
复制shallow copy是数据。因此,当您执行b=a.copy()
时,b包含与之相同的整个数据。如果更新b,请说b.updtae(c)
,则b与a会不同。如果您不只使用复制和更新b,那么更新后的值也会反映在a上。
下面是示例
a={1:2}
# when not using copy
b=a
print("printing b and a ",b,a)
# output
# printing b and a {1: 2} {1: 2}
b.update({2:3}) # updateing b
print("updated value of b",b)
# output updated value of b {1: 2, 2: 3}
print(" printing a ", a) # a and b has save value
#output printing a {1: 2, 2: 3}
a={1:2}
# when using copy
b=a.copy()
print("printing a and b ",a,b)
#output printing a and b {1: 2} {1: 2}
b.update({2:3})
print(" updated value of b ",b)
# output updated value of b {1: 2, 2: 3}
print("value of a ", a) # b and a have differnet value
#output value of a {1: 2}