我回答了一些问题,但找不到真正有帮助的问题。
假设我有一个对象列表
[[Cheese(3), Cheese(2), Cheese(1)], []]
我需要编写一个函数来找到 Cheese(1) 的索引
我试过这个:
def location (search):
return self.list.index(Cheese(1))
哪个不起作用,我认为 list.index(search)
返回列表中搜索项的索引?
对于上面的列表,索引应该是 list[0][2] for Cheese(1)
最佳答案
你需要做两件事:
给你的
Cheese()
类一个__eq__
method以便 Python 知道两个实例何时具有相同的值:class Cheese(object): def __init__(self, id): self.id = id def __eq__(self, other): if isinstance(other, Cheese): return self.id == other.id return NotImplemented
使用此实现,如果两个
Cheese()
实例具有相同的id
值,则它们是相等的。如果没有
__eq__
,对Cheese()
实例的两个引用仅在涉及相同对象(身份)时才相等。list.index()
不搜索嵌套列表;您需要明确地这样做:search = Cheese(1) try: return next((i, sublist.index(search)) for i, sublist in enumerate(self.list) if search in sublist) except StopIteration: raise IndexError('{} not found in the list'.format(Cheese(1))
将返回一个包含 2 个索引的元组到外部和内部列表中,表示找到
Cheese(1)
的第一个位置。
演示:
>>> class Cheese(object):
... def __init__(self, id):
... self.id = id
... def __eq__(self, other):
... if isinstance(other, Cheese):
... return self.id == other.id
... return NotImplemented
...
>>> Cheese(1) == Cheese(1)
True
>>> Cheese(1) == Cheese(2)
False
>>> lst = [[Cheese(3), Cheese(2), Cheese(1)], []]
>>> next((i, sublist.index(Cheese(1))) for i, sublist in enumerate(lst) if Cheese(1) in sublist)
(0, 2)
关于python - 在列表中搜索对象的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21963573/