Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index from a list of objects with one of the object's attributes

I have a list of objects and I'm trying to get one object's index in that list from an attribute of the object I have (e.g. name). Similar to something like the example below:

class Employee:
    def __init__(self, name):
        self.name = name

def add_emp(name):
    employees.append(Employee(name))

employees = []
add_emp('Emp1')

Now I'm trying to get the index of 'Emp1' in the list self.employees (here '0'). I tried this here:

print(employees.index(filter(lambda x: x.name == 'Emp1', employees)))

but he tells me that 'ValueError: < filter object at 0xblabla > is not in list'. What do I have to change or is there a better option to handle this?

like image 333
hlzl Avatar asked Mar 07 '23 17:03

hlzl


2 Answers

Well don't search for the filter itself, search for what the filter finds. For example, next(filter(...)) instead of filter(...).

But really better just use enumerate:

print(next(i for i, x in enumerate(employees) if x.name == 'Emp1'))

Or you could create a list of names and ask that for the index:

print([x.name for x in employees].index('Emp1'))

It's less efficient, though.

like image 105
Stefan Pochmann Avatar answered Apr 27 '23 17:04

Stefan Pochmann


Because filter() returns a filter object, an approach would be converting it to a list and take the element with index 0:

print(employees.index(list(filter(lambda x: x.name == 'Emp1', employees))[0]))

But, the best approach would be using enumerate():

def get_employee_index(name):
    for i, e in enumerate(employees):
        if e.name == name:
            return i
    return -1  # for not found employee

Output:

>>> get_employee_index('Emp1')
0
like image 38
ettanany Avatar answered Apr 27 '23 16:04

ettanany