How to uniq a list of objects?

How to uniq list objects in Python, save order?

def Test(object):
    def __init__(self,p1,p2):
        self.p1 = p1
        self.p2 = p2
lst = [Test(1,2), Test(2,3), Test(1,2)]

Two uniq objects if

Test1.p1 == Test2.p1 and Test1.p1 == Test2.p2
+4
source share
5 answers
class Test(object):
    def __init__(self,p1,p2):
        self.p1 = p1
        self.p2 = p2

    def __eq__(self, other):
        return (other.p1 == self.p1) and (other.p2 == self.p2)

    def __hash__(self):
        return (self.p1 << 64) | self.p2

lst = [Test(1,2), Test(2,3), Test(1,2)]
from collections import OrderedDict
uniq = list(OrderedDict.fromkeys(lst, 0))
print [[item.p1, item.p2] for item in uniq]
  • If we use objects in collections hashable, we must define __hash__and __eq__.

  • I used it (self.p1 << 64) | self.p2as a hash with the assumption that the numbers p1and p2will not exceed 2 ^ 64 (18446744073709551616).

  • , . , , ( p1 p2). , . , __hash__ OrderedDict.

+5

, . ( __eq__) , , :

class Test(object):
    def __init__(self,p1,p2):
        self.p1 = p1
        self.p2 = p2

    def __eq__(self, ot):
        return self.p1 == ot.p1 and self.p2 == ot.p2


lst = [Test(1,2), Test(2,3), Test(1,2)]
new_lst = []
for x in lst:
    if x not in new_lst:
        new_lst.append(x)
+1

collections.OrderedDict:

class Test(object):
    def __init__(self, p1, p2):
        self.p1 = p1
        self.p2 = p2

lst = [Test(1,2), Test(2,3), Test(1,2)]


import collections
d = collections.OrderedDict()
for x in lst:
    key = x.p1, x.p2
    if key not in d:
        d[key] = x

for test_item in d.values():
    print(test_item.p1, test_item.p2)

1 2
2 3
0

, , , :

def unique_values(iterable):
    seen = set()
    for value in iterator:
        key = (value.p1, value.p2)
        if key not in seen:
            yield value
            seen.add(key)

lst = list(unique_values(lst))
0

-, , :

tmpset = set(lst)
uniqsorted = list(tmpset).sort()
-1

All Articles