Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the highest value from a multi dimensional array?

Tags:

python

numpy

Say I have a multi dimensional array like the following:

[
   [.1, .2, .9],
   [.3, .4, .5],
   [.2, .4, .8]
]

What would be the best* way to return a single dimension array that contains the highest value from each sub-array ([.9,.5,.8])? I assume I could do it manually doing something like below:

newArray = []
for subarray in array:
   maxItem = 0
   for item in subarray:
       if item > maxItem:
           maxItem = item
   newArray.append(maxItem)

But I'm curious if there is a cleaner way to do this?

*In this case best = fewest lines of code

like image 488
Abe Miessler Avatar asked Apr 10 '13 04:04

Abe Miessler


2 Answers

Try this:

max(array.flatten())
like image 142
Evgenii Avatar answered Sep 27 '22 19:09

Evgenii


Since you mentioned in a comment that you are using numpy ...

>>> import numpy as np
>>> a = np.random.rand(3,3)
>>> a
array([[ 0.43852835,  0.07928864,  0.33829191],
       [ 0.60776121,  0.02688291,  0.67274362],
       [ 0.2188034 ,  0.58202254,  0.44704166]])
>>> a.max(axis=1)
array([ 0.43852835,  0.67274362,  0.58202254])

edit: the documentation is here

like image 39
wim Avatar answered Sep 27 '22 20:09

wim