在做项目的过程中,遇到了一个问题,数据保存到字典中,后来发现数据不对,排查了字典的构建过程,是OK的,后来怀疑是别的部分共用了这一个字典,排查代码,发现这里应该是有问题的。
score = None
deltaScore = result.get('score', [0 for _ in range(4)]
if not score:
score = deltaScore
else:
for index in range(4):
score[index] += deltaScore[index]
代码逻辑是从字典中获取score键的值,score为None,则直接将deltaScore赋值给score,而没有注意的是dict的get方法,是将该键的的内存赋值给deltaScore,是一个list,deltaScore再赋值给score,score、deltaScore、dict中的score键共用了一份内存,在else部分,修改score,也修改了dict的值。
最主要的是要了解python的数据类型, 从以下的验证代码也可以看出:
>>> a = {"test1":[,,], "test2":[,,]}
>>> improt json
File "<stdin>", line
improt json
^
SyntaxError: invalid syntax
>>> b = a.get("test1", [ for _ in range()])
>>> print b
[, , ]
>>> for index in range():
... b[index] +=
...
>>>
>>> print b
[, , ]
>>> print a
{'test1': [, , ], 'test2': [, , ]}
>>>