Python defaultdict如何获取列表中所有值的总和?

Python defaultdict如何获取列表中所有值的总和?,python,Python,代码如下: models = [Url1, Url2, Url3, Url4, Url5, Url6, Url7, Url8, Url9, Url10] d = defaultdict(list) for model in models: getids = model.objects.values_list('keyword', 'score') for kw, score in getids: d[kw].append(score) 这使得“d”输出为:

代码如下:

models = [Url1, Url2, Url3, Url4, Url5, Url6, Url7, Url8, Url9, Url10]
d = defaultdict(list)

for model in models:

    getids = model.objects.values_list('keyword', 'score')
    for kw, score in getids:
        d[kw].append(score)
这使得“d”输出为:

defaultdict(<type 'list'>, {198: [-70, 0, 5, -70, 5, 5, 0, 0, -50, -70],     
199: [0, -70, -70, -70, -70, -70, -100, -70, -70, -70]})

我尝试了循环,但DeafultDisct似乎不像正常列表那样工作。

您可以使用
dict
综合来获取每个值的总和

 summed = {k: sum(v) for (k, v) in d.items()}
 print(summed) 
 >>> {198: -245, 199: -660}
另外,
defaultdict
的作用类似于
字典,而不是
列表

尝试以下方法:

d = defaultdict(int)

for model in models:

    getids = model.objects.values_list('keyword', 'score')
    for kw, score in getids:
        d[kw] += score

只需将键对应的列表替换为其总和

for i in d:
     d[i] = sum(d[i])

这里的关键是使用
int
作为默认工厂,这样您就可以保持一个运行总和。
for i in d:
     d[i] = sum(d[i])