字典會很好,而不是全部e局部變量:
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)
但更好的是一個defaultdict:
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'))}
綜合和好! 謝謝! –