Is it possible to use numpy.argmax with a custom field of objects in a list?

Sort of:

class Test:
    def __init__(self, n):
        self.id = n

    def __str__(self):
        return str(self.id)

my_list = []
my_list.append(Test(1))
my_list.append(Test(2))
my_list.append(Test(3))

Is it possible to get an element in a list with max or min id?

+3
source share
2 answers

You do not even need to resort to numpy.argmax()in your example. Since your objects are in the standard Python list, you can also use the max()Python built-in function :

index = max(range(len(my_list)), key=lambda i: my_list[i].id)

or

index = max(enumerate(my_list), key=lambda x: x[1].id)[0]

will also give you the index of the item with the maximum id.

+2
source

If you define an operator __cmp__for a class Test, it argmaxshould behave as expected.

+2
source

All Articles