我目前正在开发一个AppEngine应用程序,并且有一个数据存储区中的对象列表,我想根据它们的一个属性将这些对象拆分成组。我有一个解决方案,但我想检查是否有人知道更好的方法来做到这一点。
这是我目前的代码:
for report in reports:
if report.status == 'new':
new_reports.append(report)
elif report.status == 'read':
read_reports.append(report)
elif report.status == 'accepted':
accepted_reports.append(report)
elif report.status == 'deined':
denied_reports.append(report)
elif report.status == 'resubmitted':
resubmitted_reports.append(report)
欢迎任何想法!
答案 0 :(得分:3)
你可以有一个从状态到功能的字典:
d= {"new":new_reports.append,
"read":read_reports.append,
"accepted":accepted_reports.append,
"deined":denied_reports.append,
"resubmitted":resubmitted_reports.append
}
for report in reports:
d[report.status](report)
答案 1 :(得分:2)
字典会很好而不是所有的局部变量:
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'))}
答案 2 :(得分:1)
字典怎么样:
dct = {"new":new_reports, "read":read_reports, "accepted":accepted_reports, "denied":denied_reports, "resubmitted":resubmitted_reports}
for report in reports:
dct[report.status].append(report)
或者,如果词典中没有report.status
,则可以添加try / except块:
dct = {"new":new_reports, "read":read_reports,"accepted":accepted_reports, "denied":denied_reports, "resubmitted":resubmitted_reports}
for report in reports:
try:
dct[report.status].append(report)
except KeyError:
continue