forked from brennerm/PyTricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unique_by_attr.py
34 lines (24 loc) · 869 Bytes
/
unique_by_attr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#! /usr/bin/env python3
"""
If we have some sequence of objects and want to remove items with the same attribute value
Python creates a dict, where keys are value if attribute (bar in our case), values are object of the sequence.
After that the dict is transformed back to list
Note: in result we save the last from repeating elements (item2 in our case)!
"""
class Foo(object):
def __init__(self, value):
self.bar = value
def __eq__(self, other):
return self.bar == getattr(other, 'bar')
def __hash__(self):
return int(self.bar)
def __repr__(self):
return '{}'.format(self.bar)
item1 = Foo(15)
item2 = Foo(15)
item3 = Foo(5)
lst = [item1, item2, item3]
print(set(lst))
# original
unique_lst = list({getattr(obj, 'bar'): obj for obj in lst}.values())
print(unique_lst) # [item2, item3]