前言
最近在刷LeetCode,之前C語言的語法忘得快差不多了,現在經常使用Python寫代碼,而用Python寫關於數組方面的算法免不了使用循環,這里簡單總結下Python的遍歷數組的三種方式。
遍歷方式
假設:nums=[4,5,6,10,1]
#第一種,for in的語法,這種語法很方便,但是在寫Python算法里面用到的少
for num in nums: print num
#第二種是下標訪問,range生成0到數組最大長度的下標數組 for index in range(len(nums)): print index,nums[index] #第三種是enumerate生成索引序列序列,包含下標和元素 for index,num in enumerate(nums): print index, num
實際的算法面試中經常會使用第二種和第三種。
我們看下二和三的耗時。
import time
nums=range(1000000)
start=time.time()
for index in range(len(nums)):
a = nums[index]
end=time.time()
cost = end - start
print cost
start=time.time()
for index,num in enumerate(nums):
a = nums
end=time.time()
cost = end - start
print cost
遍歷方式二:0.122675895691s
遍歷方式三:0.114228963852s
可以看出第三種比第二種的性能稍微好一些,可能在數據量更大的時候會更好。
博主:測試生財(一個不為996而996的測開碼農)
座右銘:專注測試開發與自動化運維,努力讀書思考寫作,為內卷的人生奠定財務自由。
內容范疇:技術提升,職場雜談,事業發展,閱讀寫作,投資理財,健康人生。
csdn:https://blog.csdn.net/ccgshigao
博客園:https://www.cnblogs.com/qa-freeroad/
51cto:https://blog.51cto.com/14900374
微信公眾號:測試生財(定期分享獨家內容和資源)