是否可以通过列表中对象数组中的键对结果进行分组?
例如,假设我有一个调查回复表(survey_responses
),每个条目代表一个响应。调查中的一个或多个问题是多项选择,因此存储的答案可能类似于:
survey_responses.insert({
'name': "Joe Surveylover",
'ip': "127.0.0.1",
'favorite_songs_of_2009': [
{'rank': 1, 'points': 5, 'title': "Atlas Sound: Quick Canals"},
{'rank': 2, 'points': 4, 'title': "Here We Go Magic: Fangela"},
{'rank': 3, 'points': 3, 'title': "Girls: Hellhole Ratrace"},
{'rank': 4, 'points': 2, 'title': "Fever Ray: If I Had A Heart"},
{'rank': 5, 'points': 1, 'title': "Bear in Heaven: Lovesick Teenagers"}],
'favorite_albums_of_2009': [
# and so on
]})
如何按title
的{{1}}进行分组,以获得数组中每首歌曲的总分数?
答案 0 :(得分:0)
似乎您唯一的选择是在您自己的Python代码中执行此操作:
song_points = {}
for response in survey_responses.find():
for song in response['favorite_songs_of_2009']:
title = song['title']
song_points[title] = song_points.get(title, 0) + song['points']
您会在song_points
变量中获得结果。