小测试 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
原文:https://docs.quantifiedcode.com/python-anti-patterns/performance/using_key_in_list_to_check_if_key_is_contained_in_a_list.html 使用 key in list 去迭代list会潜在的花费n次迭代才能完成,n为该key在list中位置.允许的话,可以将list转成set或者dict, 因为Python在set或dict中查找元素是通过直接访问他们而不需要迭代,这会高效很
d = {: , : , : , : , : , : } def is_key_present(x): if x in d: print('Key is present in the dictionary') else: print('Key is not present in the dictionary') is_key_present() is_key_present()