我有以下列表列表:
[Racing, 100]
[Crossi, 100]
[Racing, 120]
[Racing, 130]
[Marcas, 105]
[Marcas, 109]
[Crossi, 130]
[Crossi, 104]
我想要Racing,Marcas和Crossi的总和。如果可能的话,我想在python上使用字典。像这样:
Brads{"Crossi": 334, "Marcas": 214, "Racing":350}
是否可以仅使用一个
for
循环? 最佳答案
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})
默认设置:
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}