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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM