首页 技术 正文
技术 2022年11月21日
0 收藏 909 点赞 4,017 浏览 684 个字

在做项目的过程中,遇到了一个问题,数据保存到字典中,后来发现数据不对,排查了字典的构建过程,是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': [, , ]}
>>>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,859