码迷,mamicode.com
首页 > 编程语言 > 详细

python 字典 get方法

时间:2017-07-22 12:00:30      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:过程   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]}
>>>

 

python 字典 get方法

标签:过程   class   python 字典   json   range   result   部分   not   ...   

原文地址:http://www.cnblogs.com/yuanhuikai/p/7220556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!