2016-01-15 94 views
0

我有一個對象列表,我想根據匹配屬性「壓縮」到較小的對象列表中(id)。通過在Python中匹配屬性來壓縮對象列表

class Event: 
    def __init__(self, id, type, flag): 
     self.id = id 
     self.type = type 
     self.flag = flag 

eventlist = [ 
    Event("12345", "A", 1), 
    Event("12345", "B", None), 
    Event("67890", "A", 0), 
    Event("67890", "B", None)] 

我如何得到一個新的列表,看起來像這樣?它應該優先於None定義值並忽略屬性type

compressed = [ 
    Event("12345", 1), 
    Event("67890", 0)] 

編輯:更好的公式化問題here。這可以刪除...

+0

你想刪除'type'屬性嗎?那麼爲什麼把它添加到第一位? – thefourtheye

+0

如果event.flag不是None,那麼事件中的事件就會被壓縮= [Event(id = event.id,type = None,flag = event.flag)]' –

+1

不能用'Event創建'Event'對象(「12345」,1)',因爲_all_參數是必需的。 – mhawke

回答

1

試試看。它應該工作。

eventDict={} 
for e in eventlist: 
    eventdict[e.id]=e.flag if e.flag is not None else eventDict[e.id] 
compressed = [Event(k, None, v) for k,v in eventdict.items()] 
+0

謝謝,從技術上講它有效,但爲了簡單起見,我錯過了5個'Event'對象的更多屬性。如果有更多(他們是相同的每個事件ID),我會怎麼做? – toefftoefftoeff

相關問題