在Python中为字典中的列表项分配值

时间:2018-05-30 03:39:58

标签: python dictionary

我想在列表的dict中更改一个值,但字典中具有相同列表索引的值都会更改。我在终端玩了它,你可以看到两个不同的显示器具有相同的分配方式。 https://ibb.co/fjWCCd

抱歉,我暂时无法嵌入图片。或者你可以看看这里

dict = {1:[0.0,0.0],2:[0.0,0.0]}
dict[1]
  

[0.0,0.0]

dict[1][0]
  

0.0

dict[1][0]+=1
dict
  

{1:[1.0,0.0],2:[0.0,0.0]}

dict[2][0] = 7
dict
  

{1:[1.0,0.0],2:[7,0.0]}

dict[2][1] = 3
dict
  

{1:[1.0,0.0],2:[7,3]}

std_log = [0.0,0.0]
thedict = {}
for i in range(8):
    thedict[i+1] = std_log
thedict
  

{1:[0.0,0.0],2:[0.0,0.0],3:[0.0,0.0],4:[0.0,0.0],5:[0.0,0.0],6:[0.0,0.0 ],7:[0.0,0.0],8:[0.0,0.0]}

thedict[2][1] = 6
thedict
  

{1:[0.0,6],2:[0.0,6],3:[0.0,6],4:[0.0,6],5:[0.0,6],6:[0.0,6 ],7:[0.0,6],8:[0.0,6]}

newvalue = thedict[2]
newvalue
  

[0.0,6]

newvalue[1]
  

6

newvalue[1] +=1
newvalue
  

[0.0,7]

thedict[2] = newvalue
thedict
  

{1:[0.0,7],2:[0.0,7],3:[0.0,7],4:[0.0,7],5:[0.0,7],6:[0.0,7 ],7:[0.0,7],8:[0.0,7]}

1 个答案:

答案 0 :(得分:1)

std_log = [0.0,0.0]
for i in range(8):
    thedict[i+1] = std_log

这会创建一个dict,其中所有键都与同一列表std_log相关联,因此修改一个(键,值)对会影响所有其他值(因为它们是同一个对象)。这样做:

thedict = {i+1: [0.0,0.0] for i in range(8)}

这将为每个键创建新列表,您将能够独立修改它们。