我经历了一些问题,但找不到真正有用的问题。
假设我有一个对象列表
[[Cheese(3), Cheese(2), Cheese(1)], []]
我需要编写一个函数,在那里找到Cheese(1)的索引
我试过了:
def location (search):
return self.list.index(Cheese(1))
哪个不起作用,我以为list.index(search)
会返回列表中搜索项目的索引?
对于上面的列表,索引应该是Cheese(1)的列表[0] [2]
答案 0 :(得分:5)
你需要做两件事:
为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)