Filtering nested lists according to the absolute minimum in python

Viewed 41

Within each list of lists, I want to keep only the list whose second element is the absolute minimum among all the second elements.

Without success, I've tried to use a list comprehension with filter and min(lst,key=abs).

Here is an example with three list of lists:

input_list = [[[0, -5, 'rising']], 
[[0, -5, 'boost'], [0, -2, 'rise'], [0, -1, 'increase']],
[[1, -2, 'decrease'], [0, -3, 'lower']]] 

For instance, the second list of lists is composed of three lists and the absolute minimum among the second element of each of these lists is -1, so out of this list of lists I want to only keep [0, -1, 'increase'].

Here is the desired output :

output_list = [[0, -5, 'rising'], 
[0, -1, 'increase'], 
[0, -2, 'decrease']] 
2 Answers

Use list comprehension with min() function and custom key=

input_list = [[[0, -5, 'rising']],
[[0, -5, 'boost'], [0, -2, 'rise'], [0, -1, 'increase']],
[[1, -2, 'decrease'], [0, -3, 'lower']]]

out = [min(l, key=lambda k: abs(k[1])) for l in input_list]
print(out)

Prints:

[[0, -5, 'rising'], [0, -1, 'increase'], [1, -2, 'decrease']]

You could try sorted to get the minimum:

>>> output_list = [sorted(inner_list, key=lambda x:abs(x[1]))[0]
                   for inner_list in input_list]

>>> output_list
[[0, -5, 'rising'], [0, -1, 'increase'], [1, -2, 'decrease']]
Related