Home > Software engineering >  Grouping lists based on a certain value in python and then returning the minimum of the group
Grouping lists based on a certain value in python and then returning the minimum of the group

Time:03-03

I have a list that looks this:

lst = [(1,23,45,18),(1,42,15,5),(1,29,65,91),(2,35,62,7),(2,72,39,6),(2,41,15,81),(3,45,61,23),(3,41,15,69),(3,12,15,1)]

I'd like to group the lists by the first indicee, so group 1 would be:

[(1,23,45,18),(1,42,15,5),(1,29,65,91)]

and then return the list has the minimum value in the 4th indicee (18, 5 or 91). So the result for group 1 would be:

(1,42,15,5)

Ideally the resulting list would be the list of minimums:

final_lst = [(1,42,15,5),(2,72,39,6),(3,12,15,1)]

CodePudding user response:

If lst is sorted by the first elements (if not first sort using lst.sort(key=lambda x: x[0])), then you could use itertools.groupby to group the lists by the first element, then use min with a key that compares each group by the last elements:

from itertools import groupby
out = [min(g, key=lambda x: x[-1]) for k, g in groupby(lst, lambda x: x[0])]

Output:

[(1, 42, 15, 5), (2, 72, 39, 6), (3, 12, 15, 1)]

Or if the number of tuples for each index is the same, we could get the desired outcome with sorted list slicing:

out = sorted(lst, key=lambda x: (x[0], x[-1]))[::3]
  • Related