python - 在列表中搜索对象的索引

标签 python

我回答了一些问题,但找不到真正有帮助的问题。

假设我有一个对象列表

[[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)

最佳答案

你需要做两件事:

  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() 实例的两个引用仅在涉及相同对象(身份)时才相等。

  2. 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/

相关文章:

Python xlrd.书籍 : how to close the files?

python - 重新排序 Django 模型中的字段

python - Pandas 绘制 3 个变量的图

python - 如何使用我的数组名称作为文件名?

python - 使用 Pandas 拆分数据

python - 检查 False 的正确方法是什么?

python - 列表索引必须是整数或切片,而不是 WebElement

python - Gekko 非线性优化,约束函数评估 if 语句时出现对象类型错误

python - Random.randint() 刷新后不起作用。

python - 从 Python 调用 C/C++ 代码