2016-01-15 96 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

相关问题