I would like to generate a list of unique Ids by only keeping the list that has the minimum value in element 2.
For example, given the list:
list1 = [['Id1', 1, 40],['Id1', 2, 30],['Id2', 10,40]]`
Expected output:
[['Id1', 1, 40],['Id2', 10,40]]
Here's my working example, but it's pretty clunky. I think it could probably be done with a single list comprehension.
list1 = [['Id1', 1, 40],['Id1', 2, 30],['Id2', 10,40]]
unique_list = list(set([x[0] for x in list1]))
unique_list = [[x] for x in unique_list]
for x in unique_list:
id = x[0]
min_val = min([y[1:] for y in list1 if y[0] == id])
x.extend(min_val )
print unique_list
You can use
itertools.groupbyto group by the first element in the sublists, the you can get theminwith akeyargument to sort by the remaining elements in the sublist.