python性能:不要使用 key in list 判断key是否在list里

原文: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中查找元素是通过直接访问他们而不需要迭代,这会高效很多。

反模式

  下面的代码定义了一个list类型l,然后调用 if 3 in l去检查3是否在l中。这是低效的。这后面其实是Python一直迭代list,直到找到3或者遍历完list。  

l = [1, 2, 3, 4]

# iterates over three elements in the list
if 3 in l:
    print("The number 3 is in the list.")
else:
    print("The number 3 is NOT in the list.")

推荐做法

  使用set或dict代替list

  改良的代码如下,list转成set。更高效的背后是因为Python中,set尝试直接去访问目标值而不是通过迭代list中的每个元素和目标值相比较。

s = set([1, 2, 3, 4])

if 3 in s:
    print("The number 3 is in the list.")
else:
    print("The number 3 is NOT in the list.")

猜你喜欢

转载自www.cnblogs.com/YYRise/p/9119022.html
key