前言
最近在刷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
可以看出第三种比第二种的性能稍微好一些,可能在数据量更大的时候会更好。
博主:测试生财
座右铭:专注测试与自动化,致力提高研发效能;通过测试精进完成原始积累,通过读书理财奔向财务自由。
csdn:https://blog.csdn.net/ccgshigao
博客园:https://HdhCmsTestcnblogs测试数据/qa-freeroad/
51cto:https://blog.51cto测试数据/14900374
?
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did165816