[Tutor] maximum value in a Numeric array

Kent Johnson kent37 at tds.net
Fri Dec 10 20:19:08 CET 2004

Are you using numarray? If so, there appears to be a max method of an array, so you can try

b = array([[1,2],[3,4]])

Note that your method of finding the max row, then finding the max in the row, will not in general 
give the correct result. Sequences are compared lexicographically - the first elements are compared, 
and only if they match will the second elements be compared. Using plain lists:

 >>> b=[ [3,2], [1,4] ]
 >>> max(b)
[3, 2]
 >>> max(max(b))

You can use a list comprehension to do what you want
 >>> max([max(l) for l in b])

or in Python 2.4 you can use a generator expression and avoid creating the intermediate list:
 >>> max(max(l) for l in b)


Ertl, John wrote:
> All,
> I am trying to get the maximum value in a 2-D array.  I can use max but it
> returns the 1-D array that the max value is in and I then I need to do max
> again on that array to get the single max value.
> There has to be a more straightforward way...I have just not found it.
>>>>b = array([[1,2],[3,4]])
> array([3, 4])
>>>>c = max(b)
> 4
> I could also flatten the array to 1 D first then do max but the array I am
> going to be working with is fairly large.
> Thanks 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list