【发布时间】: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 你必须迭代它