Python"in"运算符速度

Ans*_*shi 7 python size time 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
Run Code Online (Sandbox Code Playgroud)

A> B?

len*_*310 24

摘要:

list - Average: O(n)
set/dict - Average: O(1), Worst: O(n)
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅


Tim*_*ers 7

对此没有一般的答案:它取决于的类型,a特别是b.例如,如果b是列表,则是,in采用最坏情况时间O(len(b)).但是,例如,如果b是字典或集合,则in需要预期时间O(1)(即,恒定时间).

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