5
in
運算符的運行速度與python的長度成正比嗎?Python「in」運算符速度
所以,
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> B?
in
運算符的運行速度與python的長度成正比嗎?Python「in」運算符速度
所以,
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> B?
對此沒有一般的答案:它取決於a
,特別是b
的類型。例如,如果b
是列表,那麼是的,in
需要最壞情況時間O(len(b))
。但是,例如,如果b
是字典或集合,則in
取預期時間時間O(1)
(即,恆定時間)。
關於「是A> B?」,您沒有定義A
或B
。如上所述,您的in
哪個語句運行得更快沒有一般答案。
所以如果我需要檢查一個字符串是否存在作爲一個字典中的鍵。那麼它將花費O(1)。但如果我需要查看一個字符串是否出現在列表中,那麼O(n)是正確的? –
或者即使我有一組字符串和一個字符串列表,set中的x將比list中的x更快? –
平均情況是。 – lennon310