现在我明白了 s.find()
之间的区别和 s.index()
在 Python 中感谢 this question ,我想知道,哪种方法更快?
如果我们必须附上 s.index()
,除了潜在的开销之外,在速度方面是否有任何显着差异?内try/except
?
最佳答案
Is there any significant difference in term of speed other than potential overheads if we have to enclose
s.index()
within atry/except
.
至少在 (C)Python 中,
find
, index
, rfind
, rindex
都是内部函数的包装器 any_find_slice
.实现是一样的。唯一的区别是
index
和 rindex
将引发 ValueError
如果发现调用any_find_slice
的结果为您是 -1
.如果您继续对这些进行计时,您会发现它们之间显然没有明显的区别:
➜ ~ python -m perf timeit -s "s = 'a' * 1000 + 'b'" "s.find('b')"
Median +- std dev: 399 ns +- 7 ns
➜ ~ python -m perf timeit -s "s = 'a' * 1000 + 'b'" "s.index('b')"
Median +- std dev: 396 ns +- 3 ns
我正在使用
perf
对于这里的时间。我猜在 Python 的其他实现中这不应该有所不同。两种方法都做同样的事情,只是在找不到请求的元素时它们的 react 方式不同。
关于python - s.find() 和 s.index() 之间哪个更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42551556/