python max of list of arrays

前端 未结 4 1631
礼貌的吻别
礼貌的吻别 2021-01-12 10:50

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:

相关标签:
4条回答
  • 2021-01-12 11:02

    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'))
    
    0 讨论(0)
  • 2021-01-12 11:04

    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.

    0 讨论(0)
  • 2021-01-12 11:10
         python 3.2
    
         a=[([6,2]),([8,3]),([4,2])]
         max(a)
    
         Its working well
    
    0 讨论(0)
  • 2021-01-12 11:18

    To have the max array along with the idx, this is what i'm using now:

    a = [array([6,2]),array([8,3]),array([4,2])]
    
    In: max_a = map(max, a)
    Out: max_a = [6,8,4]
    
    In: idx = max_a.index(max(max_a))
    Out: idx = 1
    
    In: result = a[idx]
    Out: reusult = [8,3]
    
    0 讨论(0)
提交回复
热议问题