将python dict值添加到

2024-04-20 14:20:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是在学习Python,我很难理解如何将一个键值连接到它本身。你知道吗

例如,这项工作。。。。。你知道吗

#!/usr/bin/python

dict= {}
for num in range (1,5):
        dict['total']=num

print dict['total']

这可以预料地打印“4”,因为dict['total']的值不断地被num中的值替换

我想做的是不断地将dict['total']的值与每个过程连接起来(我不需要下面打印的内容,只是为了清楚起见才包括在内)。。你知道吗

dict['total'] = 1,
dict['total'] = 3,
dict['total'] = 6,
dict['total'] = 10

我想这很简单,只要把作业线从

dict['total']=num

dict['total']+=num

但这给了我一个错误。。。。。你知道吗

Traceback (most recent call last):
  File "./count_loop.py", line 5, in <module>
    dict['total']+=num
KeyError: 'total'

我要为这个问题提前道歉。你知道吗


Tags: in内容forbin过程usrrangenum
3条回答

使用键的默认值初始化字典:

#!/usr/bin/python

dict= {'total': 0}
for num in range (1,5):
   dict['total'] += num

print dict['total']

我假设您给出的代码的预期输出是10。你知道吗

在这种情况下,只需在循环之前初始化dict['total']

dict= {'total': 0}
for num in range (1,5):
        dict['total'] += num

print dict['total']

在执行dict['total'] += num时,它就像dict['total'] = dict['total'] + num,这显然会在循环的第一个过程中抛出错误,因为dict['total']尚未定义。你知道吗

你想要的词是加法:串联就是你对列表和字符串这样的序列所做的。你知道吗

虽然您可以预先初始化dict,但这只有在您事先知道要使用的所有密钥时才有效。更灵活的解决方案的简单版本是:

try:
    d['total'] += num
except KeyError:
    d['total'] = num

但更简单更好的方法是:

from collections import defaultdict
d = defaultdict(int)
for num in range (1,5):
    d['total'] += num

当您请求一个键而它还不存在时,defaultdict只使用一个默认值来创建它,而不是失败。它调用我们给出的参数,int()给出零。你知道吗

相关问题 更多 >