简体   繁体   English

访问列表中具有特定属性的对象

[英]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.现在我想访问 Catherine 的 Employee 对象。 Is there a pythonic way to get Catherine's object?有没有一种pythonic的方式来获取凯瑟琳的对象? 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.我可以使用列表[i for i in employees if i.name=='Catherine'] ,但我想知道是否有更精确的东西,可以访问具有特定、唯一属性的员工,而无需搜索所有员工.

This is precisely what "next" can be used for, it'll return the first positive result in a list comprehension-esque format.这正是“next”的用途,它将以列表理解式格式返回第一个肯定结果。 It'll raise a StopIteration exception if none is found.如果没有找到,它将引发 StopIteration 异常。 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 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是的,你可以,这取决于你如何实现__eq__ dunder 方法......这会起作用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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