Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the min and max values of nested list by index of element in nested list

Tags:

python

list

I have a nested list like the following:

x = [[1,  5, 3,  4], 
     [5, 10, 7,  8], 
     [9,  9, 2, 12]]

I need to find to find the min and max values of the nested list transposed such that the result for min is:

1, 5, 2, 4  # 1 is the min of first column (1, 5, 9) a.s.o

and the max should be:

9, 10, 7, 12

I tried to convert it into a dataframe first and then doing max and min on the different axis but all doesn't come up as the result I want.

like image 991
A1122 Avatar asked Jan 18 '26 05:01

A1122


1 Answers

You can do the following using the built-in map, min, max functions and the zip(*...) transpositioning pattern:

min_x = list(map(min, zip(*x)))
max_x = list(map(max, zip(*x)))

Or as pointed out by Chris_Rands, this shortened form will also work:

min_x = list(map(min, *x))
max_x = list(map(max, *x))

Or use comprehensions:

min_x = [min(col) for col in zip(*x)]
max_x = [max(col) for col in zip(*x)]

If you desperately want to do it one line:

min_x, max_x = zip(*[(min(col), max(col)) for col in zip(*x)])
like image 169
user2390182 Avatar answered Jan 19 '26 17:01

user2390182



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!