标签:过程 class python 字典 json range result 部分 not ...
在做项目的过程中,遇到了一个问题,数据保存到字典中,后来发现数据不对,排查了字典的构建过程,是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":[1,2,3], "test2":[4,5,6]}
>>> improt json
File "<stdin>", line 1
improt json
^
SyntaxError: invalid syntax
>>> b = a.get("test1", [0 for _ in range(3)])
>>> print b
[1, 2, 3]
>>> for index in range(3):
... b[index] += 1
...
>>>
>>> print b
[2, 3, 4]
>>> print a
{‘test1‘: [2, 3, 4], ‘test2‘: [4, 5, 6]}
>>>
标签:过程 class python 字典 json range result 部分 not ...
原文地址:http://www.cnblogs.com/yuanhuikai/p/7220556.html