Remove partially duplicate tuples from list of tuples

前端 未结 3 834
情书的邮戳
情书的邮戳 2020-12-11 10:31

I have a list of tuples and need to delete tuples if its 1st item is matching with 1st item of other tuples in the list. 3rd item may or may not be the same, so I cannot use

3条回答
  •  佛祖请我去吃肉
    2020-12-11 11:04

    The usual way is keying a dict off whatever you want to dedupe by, for example:

    >>> a = [(0, 13, 'order1'), (14, 27, 'order2'), (14, 27, 'order2.1'), (0, 13, 'order1'), (28, 41, 'order3')] 
    >>> print(*{tup[:2]: tup for tup in a}.values()) 
    (0, 13, 'order1') (14, 27, 'order2.1') (28, 41, 'order3')
    

    This is O(n) time complexity, superior to O(n log n) groupby based approaches.

提交回复
热议问题