求问python下类似SQL中group by的推导?


现查询基于mongoengine的文档,其结构如下:


 #课程分类
class Category(EmbeddedDocument):
    name=StringField()

#课程
class Course(Document):
    title=StringField()
    category=EmbeddedDocumentField(Category)

现假定有若干分类,及若干课程文档,有没有简洁的办法查询出去重的课程分类名称,及该类课程的总数?比如:


 [
    ('课程类型1',25),
    ('课程类型2',10),
    ('课程类型3',20),
    ...
]

python mongoengine mongodb

我擦嘞闹得住菇 9 years, 7 months ago

好吧,自己搞定了


 from operator import itemgetter
from itertools import groupby

lst = [dict(category=c.category.name, title=c.title) for c in Course.objects]
lst.sort(key=itemgetter('category'))
categories = [(category, len(list(items))) for category, items in groupby(lst, key=itemgetter('category'))]

一起戳便便 answered 9 years, 7 months ago

Your Answer