jdk8 list 反转_Python遍历list,使用range和enumerate的效率区别

快速的结论

遍历一个python的list,除了需要value,同时还需要index的情况下,有两种方法:

# first way

第二种方法,即使用enumerate效率更

六个对比实验

def 

对一个1千万的list调用五个函数,时间消耗为:

C:...>python test.py
[2.04882090s] IndexWithLen() -> None
[0.85096200s] Enumerate() -> None
[1.86384080s] IndexWithoutLen() -> None
[2.49664880s] While() -> None
[0.28645550s] IN() -> None
[0.57038900s] EnumerateOnlyValue() -> None

C:...>python test.py
[2.02640900s] IndexWithLen() -> None
[0.84823220s] Enumerate() -> None
[1.87120120s] IndexWithoutLen() -> None
[2.56380380s] While() -> None
[0.31695870s] IN() -> None
[0.56945620s] EnumerateOnlyValue() -> None

C:...>python test.py
[1.98887280s] IndexWithLen() -> None
[0.85976040s] Enumerate() -> None
[1.89354520s] IndexWithoutLen() -> None
[2.51731620s] While() -> None
[0.28787060s] IN() -> None
[0.58649370s] EnumerateOnlyValue() -> None

可以得到3点结论:

  • 使用enumerate同时获得index和value比range获得index后取得value的效率高;
  • range中存在len时,效率会降低;
  • 在只需要value的情况下,直接使用in list的效率更高。

原因探索

先挖坑,继续刷leetcode,以后有时间再填坑。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值