Python列表的"in"运算符是否具有成功搜索的早期功能

tha*_*gnv 6 python search containers list python-internals

如果我有一个列表,那么我在列表中查找一个元素:

alist=[ele1, ele2, ele3, ele4,ele5,...]
if ele3 in alist:
  print "found" 
Run Code Online (Sandbox Code Playgroud)

将在ele3停止搜索alist?或者它会将所有剩余的元素运行到最后.

提前致谢!

Ray*_*ger 15

将在ele3停止搜索alist?

是的,如果找到目标,列表中的in运算符会执行早期退出的线性搜索.此外,如果目标对象与列表中的对象相同,它将绕过最终比较.

这里有一些跟踪器代码通过使比较可见来证明结果:

class Int(int):
    'Make comparisons visible'
    def __cmp__(self, other):
        print 'Comparing %s to %d' % (self, other)
        return int.__cmp__(self, other)

ele1 = Int(1)
ele2 = Int(2)
ele3 = Int(3)
ele4 = Int(4)
ele5 = Int(5)

alist = [ele1, ele2, ele3, ele4, ele5]
if ele3 in alist:
  print "found" 
Run Code Online (Sandbox Code Playgroud)

输出是:

Comparing 3 to 1
Comparing 3 to 2
found
Run Code Online (Sandbox Code Playgroud)

Python将表达式中的in运算符ele3 in alist转换为魔术方法调用,例如alist.__contains__(ele3).该列表.__包含__()方法的工作原理是这样的:

def __contains__(self, target):
    for element in self:
        if target is element or target == element:
            return True
    return False
Run Code Online (Sandbox Code Playgroud)

希望这会让这个过程变得清晰:-)