Python循环数组的方法

前言

最近在刷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

可以看出第三种比第二种的性能稍微好一些,可能在数据量更大的时候会更好。

博主:测试生财

座右铭:专注测试与自动化,致力提高研发效能;通过测试精进完成原始积累,通过读书理财奔向财务自由。

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

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

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

原文地址:https://www.cnblogs.com/qa-freeroad/p/14053653.html