2013-10-06 90 views
2

我目前正在開發一個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) 

任何想法表示歡迎!

回答

2

字典會很好,而不是全部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'))} 
+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) 
+0

我種像這樣 - 一個很好的方法對象如何綁定的提醒。 – Thomas

+0

@Thomas我喜歡這個,因爲我來自java;) –

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 
相關問題