2 回答
TA贡献1895条经验 获得超7个赞
lst = [{"Name": "John", "Score": 1}, {"Name": "John", "Score": 2}, {"Name": "Steve", "Score": 3}, {"Name": "Steve", "Score": 4}]
out = {}
for d in lst:
out.setdefault(d['Name'], []).append(d['Score'])
out = [{'Name': k, 'Score': v} for k, v in out.items()]
print(out)
印刷:
[{'Name': 'John', 'Score': [1, 2]}, {'Name': 'Steve', 'Score': [3, 4]}]
TA贡献2039条经验 获得超7个赞
使用itertools
def combine(group):
out = {}
out['Name'] = group[0]['Name']
score = []
for sub in group:
score.append(sub['Score'])
out['Score'] = score
return out
grouped = map(combine,[list(v) for k,v in groupby(x, lambda x: x['Name'])])
print(list(grouped))
[{'Name': 'John', 'Score': [1, 2]}, {'Name': 'Steve', 'Score': [3, 4]}]
添加回答
举报