gpt4 book ai didi

python - 尝试在嵌套字典中查找唯一值的总和。 (见示例!)

转载 作者:太空狗 更新时间:2023-10-29 22:20:42 27 4
gpt4 key购买 nike

假设我有这个变量 list_1,它是一个字典列表。每个字典都有一个嵌套的字典,称为“组”,其中包含一些信息,包括“名称”。

我想做的是对每个唯一组名称的分数求和

所以我正在寻找类似于以下内容的输出:

(陶瓷)总分 = (18)
(数学)总分 = (20)
(历史)总分 = (5)

我将上述信息放在括号中,因为我希望此代码能够工作而不管列表中的项目数量或代表的唯一组的数量。

list_1 变量:

    list_1 = [

{"title" : "Painting",
"score" : 8,
"group" : {"name" : "Ceramics",
"id" : 391}
},

{"title" : "Exam 1",
"score" : 10,
"group" : {"name" : "Math",
"id" : 554}
},

{"title" : "Clay Model",
"score" : 10,
"group" : {"name" : "Ceramics",
"id" : 391}
},

{"title" : "Homework 3",
"score" : 10,
"group" : {"name" : "Math",
"id" : 554}
},

{"title" : "Report 1",
"score" : 5,
"group" : {"name" : "History",
"id" : 209}
},

]

我的第一个想法是创建一个新的列表变量并附加每个唯一的组名。这是它的代码。但这是否有助于最终找到每一项的分数总和?

group_names_list = []
for item in list_1:
group_name = item["group"]["name"]
if group_name not in group_names_list:
group_names_list.append(group_name)

这给了我 group_names_list 的值:

['Ceramics','Math','History']

如有任何帮助或建议,我们将不胜感激!谢谢。

最佳答案

您可以使用字典来跟踪每个名字的分数:

score_dict = dict()
for d in list_1:
name = d['group']['name']
if name in score_dict:
score_dict[name] += d['score']
else:
score_dict[name] = d['score']

print(score_dict)

结果:{'陶瓷':18,'数学':20,'历史':5}

关于python - 尝试在嵌套字典中查找唯一值的总和。 (见示例!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53291314/

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