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⽣成索引序列序列,包含下标和元素
python获取数组长度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的测开码农)
座右铭:专注测试开发与⾃动化运维,努⼒读书思考写作,为内卷的⼈⽣奠定财务⾃由。
内容范畴:技术提升,职场杂谈,事业发展,阅读写作,投资理财,健康⼈⽣。
:测试⽣财(定期分享独家内容和资源)