如何对字典中的列表的所有值求和

时间:2019-08-19 10:15:02

标签: python

我试图对列表中的所有值求和,同时仍保持其位置:

{'swimming': ['1000', '1200'], 'fencing': ['200', '100'], 'athletics': ['600']}

添加后,输出应类似于:

{'swimming': ['2200'], 'fencing': ['300'], 'athletics': ['600']}

我尝试了一些示例,但是,它们需要列表的名称。我该如何解决这个问题?

5 个答案:

答案 0 :(得分:3)

尝试一下:

>>> d = {'swimming': ['1000', '1200']}
>>> l = map(int, d['swimming'])
>>> sum(l)
2200

在字典中浏览其每个键,如果该值包含列表中的多个项,则将它们中的每一个映射为整数格式,将它们求和,键入强制转换为字符串格式,然后放入仅包含一项的列表中在列表中保持原样。要更改整个字典,请尝试以下方法:

>>> d = {'swimming': ['1000', '1200'], 'fencing': ['200', '100'], 'athletics': ['600']}
>>> for k in d:
...   s = [str(sum(map(int, d[k])))] if len(d[k])>1 else d[k]
...   d[k] = s
...
>>> d
{'swimming': ['2200'], 'fencing': ['300'], 'athletics': ['600']}

答案 1 :(得分:1)

您可以使用循环:

d = {'swimming': ['1000', '1200']}
sumOfList =sum (int(n) for n in d['swimming'])

答案 2 :(得分:0)

dictionary = {'swimming': ['1000', '1200']}
print(sum(map(int, dictionary['swimming'])))
2200 # Output

答案 3 :(得分:0)

my_dict = {'swimming': ['1000', '1200']}
for each_list in my_dict.keys():
    my_dict[each_list] = sum(list(map(int, my_dict[each_list])))
  1. 通过按键循环字典
  2. 将列表中的数据类型从字符串转换为int,以便可以对其进行汇总:list(map(int,my_dict [each_list]))
  3. 总和列表

答案 4 :(得分:0)

您可以考虑以下解决方案:

d = {'swimming': ['1000', '1200'], 'fencing': ['200', '100'], 'athletics': ['600']}
for (k, v) in d.items():
    ints_v = map(int, v)
    d[k] = str(sum(ints_v))
print(d)