求问python下类似SQL中group by的推导?
现查询基于mongoengine的文档,其结构如下:
#课程分类
class Category(EmbeddedDocument):
name=StringField()
#课程
class Course(Document):
title=StringField()
category=EmbeddedDocumentField(Category)
现假定有若干分类,及若干课程文档,有没有简洁的办法查询出去重的课程分类名称,及该类课程的总数?比如:
[
('课程类型1',25),
('课程类型2',10),
('课程类型3',20),
...
]
我擦嘞闹得住菇
10 years, 1 month ago
Answers
好吧,自己搞定了
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 10 years, 1 month ago