Remove partially duplicate tuples from list of tuples

前端 未结 3 831
情书的邮戳
情书的邮戳 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:25

    You can get the first element of each group in a grouped, sorted list:

    from itertools import groupby
    from operator import itemgetter
    
    a = [(0, 13, 'order1'), (14, 27, 'order2'), (14, 27, 'order2.1'), (0, 13, 'order1'), (28, 41, 'order3')]
    
    result = [list(g)[0] for k, g in groupby(sorted(a), key=itemgetter(0))]
    print(result)
    

提交回复
热议问题