字典会更好,而不是所有的局部变量:
reports_by_status = {'new': [],
'read': [],
'accepted': [],
'deined': [], # denied?
'resubmitted': []}
for report in reports:
d[report.status].append(report)
但是你打错字了!通过使用status
变量中的任何数据来分配类别可能会很好地防止这种情况:
reports_by_status = {}
for report in reports:
if report.status not in reports_by_status:
reports_by_status[status] = []
reports_by_status[status].append(report)
这是一种常见的模式,所以我们有一些方法可以让它变得更好:
reports_by_status = {}
for report in reports:
reports_by_status.set_default(report.status, []).append(report)
但更好的是默认字典:
from collections import defaultdict
by_status = defaultdict(list)
for report in reports:
by_status[report].append(report)
itertools.groupby
很好,它封装了分类动作:
from itertools import groupby
by_status = {}
for category, group in groupby(reports, lambda x: x.status):
by_status[category] = list(group)
但是现在我们的循环看起来是map()
-ish,所以让我们使用列表推导:
from itertools import groupby
dict([(k:list(v)) for k, v in groupby(reports, lambda x: x.status)])
然后记住我们在 Python 2.7 中,所以我们也有字典推导:
from itertools import groupby
{k:list(v) for k, v in groupby(reports, lambda x: x.status)}
或到目前为止我最喜欢的,
from itertools import groupby
from operator import attrgetter
{k:list(v) for k, v in groupby(reports, attrgetter('status'))}