简体   繁体   中英

Accessing object with specific attribute in list

Let's say I have a list of objects that hold employee information:

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

employees = [Employee('Alice'), 
             Employee('Bob'), 
             Employee('Catherine'), 
             Employee('David')]

Each object would have more attributes, and there would be more employees, but this is simplified. Now I want to access the Employee object for Catherine. Is there a pythonic way to get Catherine's object? I know I could store the objects in a dictionary with their name as a key, but that seems redundant.

I could use a list comprehension like [i for i in employees if i.name=='Catherine'] , but I was wondering if there's something more precise, that can access an employee with a specific, unique attribute without searching all the emplooyees.

This is precisely what "next" can be used for, it'll return the first positive result in a list comprehension-esque format. It'll raise a StopIteration exception if none is found. You can add a default by wrapping the comprehension in a paren and providing a second argument as well.

next(i for i in employees if i.name=='Catherine')

https://docs.python.org/3/library/functions.html#next

Yes you can, it just depends on how you implement the __eq__ dunder method... this would work

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

    def __eq__(self, name):
        return self.name == name


employees = [Employee('Alice'),
             Employee('Bob'),
             Employee('Catherine'),
             Employee('David')]
print("Alice" in employees)

This would output

True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM