python – How can I remove duplicate items from a two-dimensional list?

Question:

list = [['03:30', 70.0], ['03:30', 135.0], ['03:30', 200.0], ['03:30', 280.0], 
['04:00', 360.0], ['04:00', 430.0], ['04:30', 473.0], ['04:30', 573.0]]

How to remove items with the same time and leave with a larger number to get it:

list = [['03:30', 280.0], ['04:00', 430.0], ['04:30', 573.0]]

Answer:

In [49]: from itertools import groupby

In [50]: res = [max(g) for _,g in groupby(lst, lambda x: x[0])]

In [51]: res
Out[51]: [['03:30', 280.0], ['04:00', 430.0], ['04:30', 573.0]]

you can explicitly specify the key for the max() function:

In [53]: res = [max(g, key=lambda x: x[1]) for _,g in groupby(lst, lambda x: x[0])]

In [54]: res
Out[54]: [['03:30', 280.0], ['04:00', 430.0], ['04:30', 573.0]]

This code groups the list of lists by the first element:

In [57]: for k,g in groupby(lst, lambda x: x[0]):
    ...:     print(k, list(g))
    ...:
03:30 [['03:30', 70.0], ['03:30', 135.0], ['03:30', 200.0], ['03:30', 280.0]]
04:00 [['04:00', 360.0], ['04:00', 430.0]]
04:30 [['04:30', 473.0], ['04:30', 573.0]]

after that we select in each group the element (list) with the maximum second element:

In [58]: for k,g in groupby(lst, lambda x: x[0]):
    ...:     print(max(g, key=lambda x: x[1]))
    ...:
['03:30', 280.0]
['04:00', 430.0]
['04:30', 573.0]
Scroll to Top