I\'ve a list like this:
[(\'192.168.1.100\', \'192.168.1.101\', \'A\'), (\'192.168.1.101\', \'192.168.1.100\', \'A\'),
(\'192.168.1.103\', \'192.168.1.101\
The straightforward, yet inefficient (O(n²)
) approach (thanks, @Rafał Dowgird!):
>>> uniq=[]
>>> for i in l: # O(n), n being the size of l
... if not (i in uniq or tuple([i[1], i[0], i[2]]) in uniq): # O(n)
... uniq.append(i) # O(1)
...
>>> uniq
[('192.168.1.100', '192.168.1.101', 'A'),
('192.168.1.103', '192.168.1.101', 'B'),
('192.168.1.104', '192.168.1.100', 'C')]
A more efficient approach using Python's Set
:
>>> uniq=set()
>>> for i in l: # O(n), n=|l|
... if not (i in uniq or tuple([i[1], i[0], i[2]]) in uniq): # O(1)-Hashtable
... uniq.add(i)
...
>>> list(uniq)
[('192.168.1.104', '192.168.1.100', 'C'),
('192.168.1.100', '192.168.1.101', 'A'),
('192.168.1.103', '192.168.1.101', 'B')]
You can sort it according to the last element:
>>> sorted(list(uniq), key=lambda i:i[2])
[('192.168.1.100', '192.168.1.101', 'A'),
('192.168.1.103', '192.168.1.101', 'B'),
('192.168.1.104', '192.168.1.100', 'C')]