Python循環數組的方法

前言

最近在刷LeetCode,以前C語言的語法忘得快差很少了,如今常用Python寫代碼,而用Python寫關於數組方面的算法免不了使用循環,這裏簡單總結下Python的遍歷數組的三種方式。面試

遍歷方式

假設:nums=[4,5,6,10,1]算法

 num  index  index,num  index, num

實際的算法面試中常常會使用第二種和第三種。數組

咱們看下二和三的耗時。ide

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 costspa

遍歷方式二:0.122675895691s
遍歷方式三:0.114228963852s.net

能夠看出第三種比第二種的性能稍微好一些,可能在數據量更大的時候會更好。orm

博主:測試生財blog

座右銘:專一測試與自動化,致力提升研發效能;經過測試精進完成原始積累,經過讀書理財奔向財務自由。

csdn:https://blog.csdn.net/ccgshigao

博客園:https://www.cnblogs.com/qa-freeroad/

51cto:https://blog.51cto.com/14900374

相關文章
相關標籤/搜索