【问题标题】:What is faster for searching items in list, in operator or index()?在 list、operator 或 index() 中搜索项目的速度更快?
【发布时间】:2012-11-12 11:34:51
【问题描述】:

来自site,它说 list.index() 是对列表的线性搜索。

而且看起来in 也是线性的。

使用其中一个有什么优势吗?

【问题讨论】:

  • 一个区别是list.index()返回列表中元素的索引。
  • 而且该链接似乎已损坏。请检查一下。
  • index() 返回索引,in 返回TrueFalse,否则如果你想优化,二分搜索很好,log n
  • @RohitJain:链接已修复(删除了末尾的斜线)。
  • @MartijnPieters。我认为您可以从这里的所有 cmets 中得出一个很好的答案。

标签: python performance list search


【解决方案1】:

如果您想比较不同的 Python 方法,例如 in 运算符与 .index(),请使用 timeit module 来测试速度差异。 Python 数据类型的复杂性记录在 http://wiki.python.org/moin/TimeComplexity

请注意in.index() 之间存在很大差异;第一个返回布尔值,后者返回找到的项目的索引(整数),否则会引发异常。因此,对于一般情况,它(稍微)慢一些:

$ python -mtimeit -s 'a = list(range(10000))' '5000 in a'
10000 loops, best of 3: 107 usec per loop
$ python -mtimeit -s 'a = list(range(10000))' 'a.index(5000)'
10000 loops, best of 3: 111 usec per loop

如果您需要针对成员资格测试进行优化,请改用set()

$ python -mtimeit -s 'a = set(range(10000))' '5000 in a'
10000000 loops, best of 3: 0.108 usec per loop

【讨论】:

    猜你喜欢
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多