If in List vs For 循环(性能) [英] If in List vs For loop (performance)
本文介绍了If in List vs For 循环(性能)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很想知道 Python 中什么速度更快
I am curious to know what is faster in Python
说我有一个清单
myList = ['a', 'b', 'c', 'd', 'e']
我有两种方法可以检查一个项目是否在列表中.
I have two ways of checking if an item is in the list.
if item in myList:
# doSomthing()
或
for element in myList:
if element == item:
# doSomething()
我知道第一种方法更pythonic",但在性能方面有区别吗?
I know that the first method is more "pythonic" but in terms of performance is there a difference?
推荐答案
在 jupyter notebook 中测试,第一个选项对于字符串搜索明显更快:
Testing in jupyter notebook, the first option is significantly faster for a string search:
设置(来自这个问题):
rndm=''.join(choices(string.ascii_uppercase + string.digits, k=100000))
测试:
%timeit 'a' in rndm
26.2 µs ± 485 ns per loop
%%timeit
for let in rndm:
if let=='a':
break
2.42 ms ± 73.7 µs per loop
注意:即使我们从 rndm
中创建一个 set()
并为搜索计时,它仍然只在 1.14 ms ± 26.9 µs per循环
Note: Even if we make a set()
out of rndm
and time the search, it still only comes in at 1.14 ms ± 26.9 µs per loop
这篇关于If in List vs For 循环(性能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文