Python:填充字典中的当前值或为其添加值

2024-09-29 17:20:27 发布

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

我有以下形式的数据

00 154
01 72
02 93
03 202
04 662
05 1297
00 256

我希望遍历每一行,并将第1列中的值作为键,将第2列的值作为值

另外,如果当前键已经存在,则在数学上将第2列的新值添加到第2列的当前值上。在

试过这个:

^{pr2}$

得到了这个:

Traceback (most recent call last):
  File "./get_idmanager_stats.py", line 25, in <module>
    if  d[a]:
KeyError: '00'

Tags: 数据mostgetstats数学call形式file
2条回答
d = collections.defaultdict(int)
for output in search_results:
   a,b = output.split()
   d[int(a)] += int(b)

这就是collections.defaultdict的用途。在

你可以简单地做

d = defaultdict(int)

以及

^{pr2}$

您将发现它不需要任何if语句就可以工作。在

相关问题 更多 >

    热门问题