在 python 中分类获取 json 个对象的总和
Get the sum of json objects categorically in python
我正在解决一个问题,我想在哈希图中明确地获取 JSON 个对象的总和。这是我对散列图应该是什么样子的想法:
{name: totalScore}
这是我的示例 JSON 数据:
[
{
"name": "Hilary Carr",
"submissions": [
{
"name": "Laudantium deleniti beatae fuga.",
"date": "05/12/2021",
"score": 37
}
]
},
{
"name": "Frederick Williamson",
"submissions": [
{
"name": "Expedita architecto voluptas autem veniam.",
"date": "03/05/2009",
"score": 47
},
{
"name": "Animi facere excepturi.",
"date": "01/02/2021",
"score": 100
}
]
}
]
这是我试过的方法
sums = {}
score = 0
for i in json_data:
for j in i['submissions']:
score += j['score']
sums[i['name']] = sums.get(i['name'], 0) + score
这是我得到的:
{
"Frederick Williamson": 184,
"Hilary Carr": 37
}
但结果应该是:
{
"Frederick Williamson": 147,
"Hilary Carr": 37
}
这可能是一个微不足道的错误,但你能帮我解决这个问题吗?
你可以用dict-comprehension来求和不同人的分数:
lst = [
{
"name": "Hilary Carr",
"submissions": [
{
"name": "Laudantium deleniti beatae fuga.",
"date": "05/12/2021",
"score": 37,
}
],
},
{
"name": "Frederick Williamson",
"submissions": [
{
"name": "Expedita architecto voluptas autem veniam.",
"date": "03/05/2009",
"score": 47,
},
{
"name": "Animi facere excepturi.",
"date": "01/02/2021",
"score": 100,
},
],
},
]
out = {d["name"]: sum(s["score"] for s in d["submissions"]) for d in lst}
print(out)
打印:
{'Hilary Carr': 37, 'Frederick Williamson': 147}
我正在解决一个问题,我想在哈希图中明确地获取 JSON 个对象的总和。这是我对散列图应该是什么样子的想法:
{name: totalScore}
这是我的示例 JSON 数据:
[
{
"name": "Hilary Carr",
"submissions": [
{
"name": "Laudantium deleniti beatae fuga.",
"date": "05/12/2021",
"score": 37
}
]
},
{
"name": "Frederick Williamson",
"submissions": [
{
"name": "Expedita architecto voluptas autem veniam.",
"date": "03/05/2009",
"score": 47
},
{
"name": "Animi facere excepturi.",
"date": "01/02/2021",
"score": 100
}
]
}
]
这是我试过的方法
sums = {}
score = 0
for i in json_data:
for j in i['submissions']:
score += j['score']
sums[i['name']] = sums.get(i['name'], 0) + score
这是我得到的:
{
"Frederick Williamson": 184,
"Hilary Carr": 37
}
但结果应该是:
{
"Frederick Williamson": 147,
"Hilary Carr": 37
}
这可能是一个微不足道的错误,但你能帮我解决这个问题吗?
你可以用dict-comprehension来求和不同人的分数:
lst = [
{
"name": "Hilary Carr",
"submissions": [
{
"name": "Laudantium deleniti beatae fuga.",
"date": "05/12/2021",
"score": 37,
}
],
},
{
"name": "Frederick Williamson",
"submissions": [
{
"name": "Expedita architecto voluptas autem veniam.",
"date": "03/05/2009",
"score": 47,
},
{
"name": "Animi facere excepturi.",
"date": "01/02/2021",
"score": 100,
},
],
},
]
out = {d["name"]: sum(s["score"] for s in d["submissions"]) for d in lst}
print(out)
打印:
{'Hilary Carr': 37, 'Frederick Williamson': 147}