gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:58:04 25 4
gpt4 key购买 nike

代码如下:

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]})

如何让它返回:

defaultdict({198: -245, 199: -660}) #sum of all numbers inside lists, returned as values to both keys.

我尝试了循环,但 deafultdict 似乎不像普通列表那样工作。

最佳答案

试试这个:

d = defaultdict(int)

for model in models:

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

关于python - defaultdict 如何获取列表中所有值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33112347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com