filter out “reversed” duplicated tuples from a list in Python

后端 未结 4 1380
滥情空心
滥情空心 2021-01-15 14:48

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\         


        
4条回答
  •  悲哀的现实
    2021-01-15 15:12

    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')]
    

提交回复
热议问题