Sevval Kahraman
Sevval Kahraman

Reputation: 1301

How to find max element index for a specific value in list composed of class objects?

I want to find a maximum elements index in a nested list for each row.

I got this error:

maxe = array[i].index(max(e_object.x for e_object in array[i]))
ValueError: 5 is not in list
class e_object():
    def __init__(self,x):
        self.x = x

array = []
array.append( [])
array[0].append(e_object(0))
array[0].append(e_object(2))
array[0].append(e_object(-3))
array[0].append(e_object(5))

array.append( [])
array[1].append(e_object(0))
array[1].append(e_object(2))
array[1].append(e_object(8))
array[1].append(e_object(5))

max_array = []
for i in range(len(array)):
    maxe = array[i].index(max(e_object.x for e_object in array[i]))
    max_array.append(maxe)

print(max_array)

How can I get this result?

[3,2]

Upvotes: 1

Views: 68

Answers (3)

Mad Physicist
Mad Physicist

Reputation: 114280

The error happens because your max effectively operates on a list of integers [0, 2, -3, 5], while index searches in a list of e_objects. There are any number of ways of fixing this issue.

The simplest is probably to just have max return the index:

max_array = [max(range(len(a)), key=lambda x: a[x].x) for a in array]

This is very similar to using numpy's argmax, but without the heavy import and intermediate memory allocations. Notice that this version does not require two passes over each list since you don't call index on the result of max.

A more long term solution would be to add the appropriate comparison methods, like __eq__ and __gt__/__lt__ to the e_object class.

Upvotes: 1

blue note
blue note

Reputation: 29071

The problem is line

maxe = array[i].index(max(e_object.x for e_object in array[i]))

You are asking the index of object.x, but the list actually contains object. Change the max function to look inside the objects x attribute

maxe = array[i].index(max(array[i], key=lambda o: o.x))

Upvotes: 1

gmds
gmds

Reputation: 19885

Use a list comprehension to convert the nested list into one of x values, and then use np.argmax:

import numpy as np

np.argmax([[element.x for element in row] for row in array], axis=1)

Output:

array([3, 2], dtype=int64)

Upvotes: 1

Related Questions