2014-05-23 87 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