【问题标题】:Get index from a list of objects with one of the object's attributes从具有对象属性之一的对象列表中获取索引
【发布时间】:2018-04-13 21:59:25
【问题描述】:

我有一个对象列表,我试图从我拥有的对象的属性(例如名称)中获取该列表中一个对象的索引。类似于下面的例子:

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

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

employees = []
add_emp('Emp1')

现在我正在尝试在列表 self.employees(此处为 '0')中获取 'Emp1' 的索引。我在这里试过这个:

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

但他告诉我 'ValueError: is not in list'。我需要改变什么或者有更好的选择来处理这个问题?

【问题讨论】:

  • 您可以使用enumerate 函数,它以i, o 的形式返回元组的迭代器,其中i 是索引,o 是实际对象。
  • @hkzl 你必须迭代它

标签: python oop arraylist


【解决方案1】:

因为filter() 返回一个过滤器对象,一种方法是将其转换为列表并获取索引为 0 的元素:

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

但是,最好的方法是使用enumerate()

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

输出:

>>> get_employee_index('Emp1')
0

【讨论】:

  • 第一种方法,使用过滤器,实际上对我不起作用,因为他抱怨 list index 超出范围。然而,第二个选项,你和其他人说无论如何都更好,效果很好。非常感谢!
【解决方案2】:

不要搜索过滤器本身,而是搜索过滤器找到的。例如,next(filter(...)) 而不是 filter(...)

但最好还是使用enumerate:

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

或者您可以创建一个名称列表并要求索引:

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

不过效率较低。

【讨论】:

  • 你和@ettanany 的答案都非常好,但是这个在一行中完成了这项工作,所以我把它作为接受的答案。非常感谢大家!
猜你喜欢
  • 2021-07-23
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 2013-10-10
相关资源
最近更新 更多