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
可以看出第三种比第二种的性能稍微好一些,可能在数据量更大的时候会更好。
博主:测试生财(一个不为996而996的测开码农)
座右铭:专注测试开发与自动化运维,努力读书思考写作,为内卷的人生奠定财务自由。
内容范畴:技术提升,职场杂谈,事业发展,阅读写作,投资理财,健康人生。
csdn:https://blog.csdn.net/ccgshigao
博客园:https://www.cnblogs.com/qa-freeroad/
51cto:https://blog.51cto.com/14900374
微信公众号:测试生财(定期分享独家内容和资源)
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步