0

Python 菜鸟在这里。我的数据库中有一个名为“data”的对象,我想编写一些python,它将从每组student_id中选择最低分数......并为找到的每个最小记录获取唯一的ObjectId?

{u'student_id': 197, u'_id': ObjectId('50906d7fa3c412bb040eb88d'), u'type': u'homework', u'score': 10.90872422518918}
{u'student_id': 197, u'_id': ObjectId('50906d7fa3c412bb040eb88e'), u'type': u'homework', u'score': 88.3871242475841}
{u'student_id': 198, u'_id': ObjectId('50906d7fa3c412bb040eb892'), u'type': u'homework', u'score': 17.46279901047208}
{u'student_id': 198, u'_id': ObjectId('50906d7fa3c412bb040eb891'), u'type': u'homework', u'score': 76.18366499496366}
{u'student_id': 199, u'_id': ObjectId('50906d7fa3c412bb040eb895'), u'type': u'homework', u'score': 49.34223066136407}
{u'student_id': 199, u'_id': ObjectId('50906d7fa3c412bb040eb896'), u'type': u'homework', u'score': 58.09608083191365}

谢谢你的麻烦......这是我的代码......

import pymongo

from itertools import groupby
from pymongo import Connection


connection = Connection('localhost', 27017)

db = connection.students

data = db.grades.find({'type' : 'homework'}).sort([('student_id',pymongo.ASCENDING),('score',pymongo.ASCENDING)])



for student_id, items in groupby(data, lambda s: s['student_id']):
    lowest_score = min(i['score'] for i in items)

    print lowest_score
4

2 回答 2

2

我认为您可能能够以不同的方式进行最低检查并获得 ObjectID 而不是最小值的分数。这是我的做法:

lowest_id = min(items, key=lambda i: i['score'])['_id']

现在,有可能(实际上,很可能)您可以在数据库本身中执行类似的操作,并且可能会有更好的性能。但是,如果您的数据集不太笨重,上述方法可能工作得很好。

于 2012-11-09T23:56:26.593 回答
1

不确定您是否仍然可以访问 student_id 字段,如果可以,您可以替换:

lowest_score = min(i['score'] for i in items)

和:

lowest_score = min((i['score'],i['student_id']) for i in items)
于 2012-11-09T23:54:26.800 回答