使用 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.")