0

我有类似下面代码的情况。我想找到对象 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
4

3 回答 3

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
于 2013-06-05T16:38:30.027 回答
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
于 2013-06-05T16:40:04.633 回答
0

最明显的方式:

for index, value in enumerate(l):
    if isinstance(value,A):
        return (index, value)
于 2013-06-05T16:39:56.313 回答