python - Python 的 'in' 列表运算符是否具有成功搜索的早期输出

标签 python list search containers python-internals

如果我有一个列表,那么我会通过以下方式查找列表中的元素:

alist=[ele1, ele2, ele3, ele4,ele5,...]
if ele3 in alist:
  print "found" 

会停止从 ele3 的列表中搜索吗? 或者它将遍历所有剩余元素直到结束。

提前致谢!

最佳答案

Will in stop a search from alist at ele3 ?

是的,如果找到目标,列表中的 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" 

输出是:

Comparing 3 to 1
Comparing 3 to 2
found

Python 将表达式 ele3 in alist 中的 in 运算符翻译成 magic method call例如 alist.__contains__(ele3)list.__contains__()方法是这样的:

def __contains__(self, target):
    for element in self:
        if target is element or target == element:
            return True
    return False

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

关于python - Python 的 'in' 列表运算符是否具有成功搜索的早期输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25151927/

相关文章:

python - 在 python 函数调用的参数列表中嵌套生成器表达式

r - 嵌套列表的条件子集

javascript - 如何在 JavaScript 中过滤这些搜索结果?

search - 在 emacs 中实现增量搜索

python - 文本处理 - Python 与 Perl 的性能对比

python - 如何将图像保存到具有图像 url 的 mongodb?

python - 如何将多维数据框作为联合添加到另一个多维数据框?

java - 在 arraylist for 循环中执行 Collections.swap() 是否安全?

python - 如何接受多个元素的列表作为命令行参数?

python - python 列表的子集