在列表中查找对象类型的实例

时间:2013-06-05 16:34:42

标签: python list search

我遇到类似下面代码的情况。我想找到对象A的第一个实例的索引。我能做到的最快的方法是什么?

我知道有很多方法可以浏览整个列表并找到它,但有没有办法在第一个找到后停止搜索?

class A():
    def __init__(self):
        self.a = 0
    def print(self):
        print(self.a)

l = [0, 0, A(), 0, A(), 0]
print(l.index(type(A))) # this does not work

3 个答案:

答案 0 :(得分:3)

你必须测试每个对象;使用列表推导和enumerate()来获取所有匹配的索引:

[i for i, ob in enumerate(l) if isinstance(ob, A)]

或获取第一个索引,使用next()和生成器表达式:

next((i for i, ob in enumerate(l) if isinstance(ob, A)), None)

演示:

>>> [i for i, ob in enumerate(l) if isinstance(ob, A)]
[2, 4]
>>> next((i for i, ob in enumerate(l) if isinstance(ob, A)), None)
2

答案 1 :(得分:2)

class A():
    def __init__(self):
        self.a = 0
    def __eq__(self,other): #this overrides the equality check
        if isinstance(other,A):
           return self.a==other.a
    def print(self):
        print(self.a)

l = [0, 0, A(), 0, A(), 0]
print(l.index(A()))#now this should work
print A() in l

a1 = A()
a2 = A()
a1 == a2 #True
a1.a = 2
a1 == a2 #False
a2.a = 2
a1 == a2 #True
a2.a = 5
a1 < a2 #Error we would need to overload __cmp__ or __lt__ methods for this to work

答案 2 :(得分:0)

最明显的方式:

for index, value in enumerate(l):
    if isinstance(value,A):
        return (index, value)
相关问题