我在我的数据库中有一个名为“item”的对象,我想写一些python,它将从每组student_id中选择最低分数....我是一个完整的python noob ...怎么会我这样做了?
{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}
更新:
在运行我的代码时遇到一些问题...我可以完成一些完整性检查吗?我收到了这个错误...
NameError: name 'getResultFromDatabase' is not defined
感谢您的麻烦......这是我的代码......
import pymongo
from itertools import groupby
from pymongo import Connection
data = getResultFromDatabase()
connection = Connection('localhost', 27017)
db = connection.students
item = db.grades.find({'type' : 'homework'}).sort([('student_id',pymongo.ASCENDING),('score',pymongo.ASCENDING)])
for id, items in groupby(data, lambda s: s['student_id']):
lowest_score = min(i['score'] for i in items)
print lowest_score
答案 0 :(得分:3)
groupby
做你想做的事:
from itertools import groupby
data = getResultFromDatabase()
for id, items in groupby(data, lambda s: s['student_id']):
lowest_score_entry = min(items, key=lambda i: i['score'])
print lowest_score_entry['score'], lowest_score_entry['_id']