Python“in”运算符速度

时间:2013-11-27 05:54:42

标签: python time size in-operator

in运算符在python中的速度是否与可迭代的长度成比例?

所以,

len(x) #10
if(a in x): #lets say this takes time A
    pass

len(y) #10000
if(a in y): #lets say this takes time B
    pass

是A>乙

2 个答案:

答案 0 :(得分:24)

以下摘要:

list - Average: O(n)
set/dict - Average: O(1), Worst: O(n)

有关详细信息,请参阅this

答案 1 :(得分:7)

对此没有一般性答案:它取决于a的类型,尤其是b的类型。例如,如果b是一个列表,那么是,in采用最坏情况时间O(len(b))。但是,例如,如果b是dict或set,那么in会占用预期时间O(1)(即常量时间)。

关于“是A> B?”,您没有定义AB。如上所述,对于哪些in语句运行得更快,没有一般答案。