Remove partially duplicate tuples from list of tuples

前端 未结 3 829
情书的邮戳
情书的邮戳 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 10:59

    You should avoid modifying your list in place while iterating over it. Instead, you can use the popular itertools unique_everseen recipe, also available in 3rd party more_itertools. Just use operator.itemgetter in the key argument:

    from more_itertools import unique_everseen
    from operator import itemgetter
    
    res = list(unique_everseen(L, key=itemgetter(0, 1)))
    

    This solution takes O(n) time, but is generally less efficient than a dictionary-based solution, although it is arguably clearer in its intention.

提交回复
热议问题