基于键的总和分组的字典集合的Python列表
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于键的总和分组的字典集合的Python列表相关的知识,希望对你有一定的参考价值。
伙计,我的字典如下所示
d = ['status': 'Red', 'name': 'Alex', 'status': 'Red', 'name': 'Alex',
'status': 'Green', 'name': 'Alex', 'status': 'Yellow', 'name': 'Peter',
'status': 'Green', 'name': 'Mike', 'status': 'Yellow', 'name': 'Alex',
'status': 'Green', 'name': 'Peter', 'status': 'Red', 'name': 'Mike',
'status': 'Yellow', 'name': 'Alex']
我正在尝试以最有效的方式进行汇总,我想要的输出应如下所示
d = ["name": "Alex", "Red": 2, "Green": 1, "Yellow": 2,
"name": "Peter", "Red": 0, "Green": 1, "Yellow": 1,
"name": "Mike", "Red": 1, "Green": 1, "Yellow": 0
]
我可以按总数进行汇总,但在按'状态'值进行分组时遇到麻烦
from collections import Counter
output = Counter(i['name'] for i in d)
非常感谢任何帮助-问候
答案
实现此目的的一种方法是创建一个字典并存储值,最后将其转换为所需的格式。就我而言,我创建了一个以名称为键的空dict并更新值(与以较低效率O(N ^ 2)直接创建它相比,这相当于O(N))。相同的代码:
d = ['status': 'Red', 'name': 'Alex', 'status': 'Red', 'name': 'Alex',
'status': 'Green', 'name': 'Alex', 'status': 'Yellow', 'name': 'Peter',
'status': 'Green', 'name': 'Mike', 'status': 'Yellow', 'name': 'Alex',
'status': 'Green', 'name': 'Peter', 'status': 'Red', 'name': 'Mike',
'status': 'Yellow', 'name': 'Alex']
res =
for val in d:
if val["name"] not in res:
res[val["name"]] = "Red": 0, "Green": 0, "Yellow": 0
res[val["name"]][val["status"]] += 1
data = ["name": key,
"Red": res[key]["Red"],
"Green": res[key]["Green"],
"Yellow": res[key]["Yellow"] for key in res.keys()]
以上是关于基于键的总和分组的字典集合的Python列表的主要内容,如果未能解决你的问题,请参考以下文章