小测试
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已经删除了该函数。