小測試
in
del.py
import datetime cur = datetime.datetime.now() num = 1 a_list = {"a":1, "b":2, "c":3} while num < 100000: if "a" in a_list: pass num += 1 now = datetime.datetime.now() print (now - cur).total_seconds()
has_key
del2.py
import datetime cur = datetime.datetime.now() num = 1 a_list = {"a":1, "b":2, "c":3} while num < 100000: if a_list.has_key("a"): pass num += 1 now = datetime.datetime.now() print (now - cur).total_seconds()
結果
$python del.py 0.02399 $python del2.py 0.030393
官網
官方文檔推薦用 key in dict 的語法,因為它更短更通俗易懂。has_key是老舊遺留的api,為了支持2.2之前的代碼留下的。Python3已經刪除了該函數。