Python的列表“in”操作符是否有一个成功搜索的早期布局

2024-09-27 19:16:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

会在ele3停止从列表中搜索吗? 或者它将运行所有剩余的元素到最后。在

提前谢谢!在


Tags: 方法in元素列表ifprintfoundalist
3条回答

in一旦找到该项,就停止搜索该列表。在

Source

条件if ele3 in alist:的目的是,检查ele3是否存在于列表中。一旦找到,就不需要处理其他元素。在

如果你有条件

False and True

如果第一个元素是False,则不需要处理rest语句。因为剩下的语句总是False。在

同样的规则也适用于您的条件,一旦找到,则无需处理其他元素。在

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" 

输出为:

^{pr2}$

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

希望这能让整个过程清晰明了:-)

相关问题 更多 >

    热门问题