python - Python字典中的变量作为值
问题描述
我有 4 个私有变量:
__first = 0
__second = 0
__third = 0
__fourth = 0
我将它们添加到这样的字典中:
numbers = {one: __first, two: __second, three: __third, fourth: __fourth)
当我这样做__first += 1
时,字典中的值不会改变,而原始变量会改变。
有什么帮助吗?
解决方案
请检查这是否适合您。我只是根据键更新了值。你会得到一个刷新字典。您可能会问自己为什么如果我更新他们不会在字典中更新的变量?他们会第一次这样做,但第二次他们不会,因为它们被分配在只能通过索引位置 [x] 位置访问的其他内存块中。因此,如果您需要更新它,您可能需要在这种情况下根据它们的键更新值。
__first = 0
__second = 0
__third = 0
__fourth = 0
dict = {"first": __first,
"second": __second,
"third": __third,
"fourth": __fourth}
def updateDict(dict, new_key, new_value):
for key, value in dict.items():
if key == new_key:
dict[key] = new_value
print(dict)
return dict
dict = updateDict(dict, "first", 1)
# {'first': 1, 'second': 0, 'third': 0, 'fourth': 0}
dict = updateDict(dict, "second", 10)
# {'first': 1, 'second': 10, 'third': 0, 'fourth': 0}
推荐阅读
- angular - 如何禁用垫下拉选项从一到二?
- java - 如何将函数值传递给百里香叶
- angular - Gulp 在开始时和实时后编译所有内容
- excel - 如何删除 Excel 筛选器中的数字
- android - QMake/QtCreatir 将二进制文件复制到给定位置的好策略是什么
- apache-kafka - 动态配置retention.ms不适用于kafka主题
- python - 熊猫不会将数据框写入excel文件,它仍然是空的
- redhat - NagiosXI 安装失败:[Errno 256] 没有更多镜像可以尝试
- java - 读取带有“跟随”标志的容器日志,线程被永远阻塞
- mysql - 根据sql中的另一个表显示所有日期的计数?