Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python max of list of arrays

I have a list of arrays like:

a = [array([6,2]),array([8,3]),array([4,2])]

I tried max(a) which returns the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I want it to return either a list or array like:

In: max(a)
Out: [8,3]

I don't want to convert the inner arrays to list, because the size of the list is very big. Also I purposefully created like that to perform array operations.

like image 246
Thiru Avatar asked Nov 05 '12 07:11

Thiru


2 Answers

The easiest way is to convert to tuple/lists for the sake of comparison (or implement the comparison yourself):

>>> max(a, key=tuple)
array([8, 3])

Note this is the builtin max and not np.max

EDIT:

For multi dimensional arrays, use the .tolist method:

max(a, key=operator.methodcaller('tolist'))
like image 155
JBernardo Avatar answered Oct 13 '22 09:10

JBernardo


Defining max on arrays is, as it says in the exception, ambiguous. If we have the following arrays: [6, 2], [5, 1], then I guess the output should be [6, 2], but if we have the following example: [6, 2], [7, 1] what would then the output have to be.

In fact there are so many different definitions of max here. If we take the arrays to be vectors then max can be the magnitude of them, or the vector that has maximum x coord, etc. Max can just as well compare the length of the arrays in the list and return the one with most elements or in the case of a tie the first one of the ones with equal length.

My suggestion is to create a class abstracting your array structures and define the max operation there with exactly the outcome you expect.

like image 45
Konstantin Dinev Avatar answered Oct 13 '22 11:10

Konstantin Dinev