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

相关文章
相关标签/搜索