Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return min/max of multidimensional in Python?

I have a list in the form of

[ [[a,b,c],[d,e,f]] , [[a,b,c],[d,e,f]] , [[a,b,c],[d,e,f]] ... ] etc.

I want to return the minimal c value and the maximal c+f value. Is this possible?

like image 755
John Smith Avatar asked Dec 16 '11 18:12

John Smith


People also ask

How do you find the max and min value of a 2D array in Python?

We can find the minimum and maximum values from the each row of a 2D numpy array by using the "min" and "max" functions available in the Numpy library.

How do you find the smallest number in a 2D array in Python?

min to return the minimum value, or equivalently for an array arrname use arrname. min() . As you mentioned, numpy. argmin returns the index of the minimum value (of course, you can then use this index to return the minimum value by indexing your array with it).


3 Answers

For the minimum c:

min(c for (a,b,c),(d,e,f) in your_list)

For the maximum c+f

max(c+f for (a,b,c),(d,e,f) in your_list)

Example:

>>> your_list = [[[1,2,3],[4,5,6]], [[0,1,2],[3,4,5]], [[2,3,4],[5,6,7]]]
>>> min(c for (a,b,c),(d,e,f) in lst)
2
>>> max(c+f for (a,b,c),(d,e,f) in lst)
11
like image 56
Andrew Clark Avatar answered Nov 02 '22 14:11

Andrew Clark


List comprehension to the rescue

a=[[[1,2,3],[4,5,6]], [[2,3,4],[4,5,6]]]
>>> min([x[0][2] for x in a])
3

>>> max([x[0][2]+ x[1][2] for x in a])
10
like image 29
Fredrik Pihl Avatar answered Nov 02 '22 15:11

Fredrik Pihl


You have to map your list to one containing just the items you care about.

Here is one possible way of doing this:

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

minc = min(l[0][2] for l in x)
maxcf = max(l[0][2]+l[1][2] for l in x)

The contents of the min and max calls is what is called a "generator", and is responsible for generating a mapping of the original data to the filtered data.

like image 1
Nate Avatar answered Nov 02 '22 15:11

Nate