在字典理解中对列表求和

Sum over list in dict comprehension

我正在研究听写理解。我从一个值为整数列表的字典开始,我想将其转换为具有相同键的字典,但值是原始列表的总和。这是一个可重现的例子:

n_dict = {4: [4,1,6], 3: [5,3,9], 2: [8,2,10]}
n_sum = {n_key: sum(n) for n_key in n_dict.keys() for n in n_dict[n_key]}
print(n_sum)
# expected result: {4: 11, 3: 17, 2: 20}

不幸的是,我收到以下类型错误,我不知道为什么:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    n_sum = {n_key: sum(n) for n_key in n_dict.keys() for n in n_dict[n_key]}
  File "main.py", line 3, in <dictcomp>
    n_sum = {n_key: sum(n) for n_key in n_dict.keys() for n in n_dict[n_key]}
TypeError: 'int' object is not iterable

遍历items,同时遍历键和对应的值:

n_dict = {4: [4, 1, 6], 3: [5, 3, 9], 2: [8, 2, 10]}
n_sum = {key: sum(value) for key, value in n_dict.items()}
print(n_sum)

输出

{4: 11, 3: 17, 2: 20}

您不需要遍历列表项并尝试使用嵌套循环为列表中的每个 int 调用 sum

n_dict = {4: [4,1,6], 3: [5,3,9], 2: [8,2,10]}
n_sum = {n_key: sum(n_dict[n_key]) for n_key in n_dict.keys()}
print(n_sum)

Demo