使用一个字典(Python)对列表列表的不同元素求和

时间:2016-11-18 12:00:55

标签: python list dictionary sum

我有这个列表清单:

    [Racing, 100]
    [Crossi, 100]
    [Racing, 120]
    [Racing, 130]
    [Marcas, 105]
    [Marcas, 109]
    [Crossi, 130]
    [Crossi, 104]

我想要赛车,马卡斯和克罗斯的总和。如果有可能,我想用python上的字典来做。像这样:

    Brads{"Crossi": 334, "Marcas": 214, "Racing":350}

只有一个for循环可以做到吗?

5 个答案:

答案 0 :(得分:1)

您可以将collections.defaultdict用于此

from collections import defaultdict

l = [['Racing', 100],
     ['Crossi', 100],
     ['Racing', 120],
     ['Racing', 130],
     ['Marcas', 105],
     ['Marcas', 109],
     ['Crossi', 130],
     ['Crossi', 104]]

d = defaultdict(int)
for key, value in l:
    d[key] += value

print(d)

的输出
defaultdict(<class 'int'>, {'Marcas': 214, 'Racing': 350, 'Crossi': 334})

答案 1 :(得分:1)

你可以这样做:

list_of_list = [
    ['Racing', 100],
    ['Crossi', 100],
    ['Racing', 120],
    ['Racing', 130],
    ['Marcas', 105],
    ['Marcas', 109],
    ['Crossi', 130],
    ['Crossi', 104]
]

people = {}

for selected_list in list_of_list:
    name = selected_list[0]
    if name in people:
        people[name] += selected_list[1]
    else:
        people[name] = selected_list[1]

答案 2 :(得分:1)

from collections import defaultdict
list_ = [['Racing', 100],['Crossi', 100],['Racing', 120],['Racing', 130],['Marcas', 105],['Marcas', 109],['Crossi', 130],['Crossi', 104]]
dic = defaultdict(int)
for i in list_:
    dic[i[0]] += i[1]
print(dic)

出:

defaultdict(<class 'int'>, {'Marcas': 214, 'Crossi': 334, 'Racing': 350})

setdefault:

list_ = [['Racing', 100],['Crossi', 100],['Racing', 120],['Racing', 130],['Marcas', 105],['Marcas', 109],['Crossi', 130],['Crossi', 104]]
d = {}
for k,v in list_:
    d[k] = d.setdefault(k,0) + v
print(d)

出:

{'Marcas': 214, 'Crossi': 334, 'Racing': 350}

答案 3 :(得分:0)

如果不导入集合,您可能会使用dict.get()获得相同的行为:

my_dict = {}
for k, v in l:
    my_dict[k] = my_dict.get(k, 0) + v  # Here `my_dict.get(k)` will return the value
                                        # if `k` key is found, else will return 0
# Final content of `my_dict`:
# {'Racing': 350, 
#  'Marcas': 214, 
#  'Crossi': 334}

其中l是问题中提到的列表。

答案 4 :(得分:0)

通过列表上的更多迭代,您可以以单行方式解决问题。

l = [['Racing', 100], ['Crossi', 100], ['Racing', 120], ['Racing', 130],
     ['Marcas', 105], ['Marcas', 109], ['Crossi', 130], ['Crossi', 104]]

print dict((el[0], sum(v for k, v in l if k == el[0])) for el in l)