2014-05-23 86 views
1

在下面的代碼我試圖找到重複的對象,並將其分配給原來的對象list.Is那裏做同樣的蟒蛇過濾對象列表

user_list = [] 
unique_user = [] 
for user in users: 
    if user.id not in user_list: 
     user_list.(user.id)  
     unique_user.append(user) 
    users = unique_user 

編輯

users = [<User {u'username': u'rr', u'name': u'rr', u'enabled': True, u'tenantId': u'81ec14658b764c6799871b9e5573e76f', u'id': u'6bdf7afb1d2e4bd19f7d807063720ac3', u'email': u'[email protected]'}>, <User {u'username': u'rr', u'name': u'rr', u'enabled': True, u'tenantId': u'81ec14658b764c6799871b9e5573e76f', u'id': u'6bdf7afb1d2e4bd19f7d807063720ac3', u'email': u'[email protected]'}>, <User {u'username': u'y', u'name': u'y', u'enabled': True, u'tenantId': u'81ec14658b764c6799871b9e5573e76f', u'id': u'd4afeeb8bc554f2083f93f68638dac0d', u'email': u'[email protected]'}>] 
+0

使用'set'maybe? – Gogo

+0

什麼是'用戶'? – juanchopanza

+0

什麼是<>? – Gogo

回答

5
的優化方法
users = set(users) 

將一個迭代變成一組無序的獨特元素。 Docs

的對象必須是hashable

class A(object): 
    def __init__(self, a): 
     self.a = a 
    def __eq__(self, other): 
     return self.a == other.a 
    def __hash__(self): 
     return hash(self.a) 

set([A(2), A(2), A(1)]) 
{<__main__.A at 0x2676090>, <__main__.A at 0x2676110>} 

編輯:如何使它們可哈希

for user in users: 
    user.__eq__ = lambda self, other: self.id == other.id 
    user.__hash__ = lambda self: hash(self.id) 

unique_users = set(users) 

# If you want to remove the attributes to leave them as they were: 

unique_users = [delattr(usr, __hash__) for usr in unique_users] 
+0

集對對象無效 – Rajeev

+0

@Rajeev確定'set'與對象一起工作:) –

+0

對象必須是可哈希的(https://docs.python.org/2/glossary.html#term-hashable)。你需要定義'__hash__'和'__eq__' – Davidmh