前言
最近在刷LeetCode,之前C语言的语法忘得快差不多了,现在经常使用Python写代码,而用Python写关于数组方面的算法免不了使用循环,这里简单总结下Python的遍历数组的三种方式。
遍历方式
假设:nums=[4,5,6,10,1]num index index,num 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
可以看出第三种比第二种的性能稍微好一些,可能在数据量更大的时候会更好。