range(len(list)) or enumerate(list)?(范围(len(list))还是枚举(list)?)
问题描述
可能重复:
只需要索引:枚举或(x)范围?
哪些会被认为更好/更清晰/更快/更Pythonic"?我不关心列表L的内容,只关心它有多长.
Which of these would be considered better/clearer/faster/more 'Pythonic'? I don't care about the content of the list L, just how long it is.
a = [f(n) for n, _ in enumerate(L)]
或
a = [f(n) for n in range(len(L))]
如果有什么不同,f 函数也会使用 len(list).
If it makes any difference, the function f makes use of len(list) as well.
推荐答案
一些快速的计时运行似乎给使用 range() 的第二个选项比 enumerate()代码>:
Some quick timing runs seem to give the 2nd option using range() a slight edge over enumerate():
timeit a = [f(n) for n, _ in enumerate(mlist)]
10000 loops, best of 3: 118 us per loop
timeit a = [f(n) for n in range(len(mlist))]
10000 loops, best of 3: 102 us per loop
只是为了好玩,使用 xrange() (Python v2.7.2)
and just for fun using xrange() (Python v2.7.2)
timeit a = [f(n) for n in xrange(len(mlist))]
10000 loops, best of 3: 99 us per loop
我倾向于首先使用可读代码,然后使用 xrange()(如果可用)(即 Pre-Python v 3.x),然后是 range() 和 enumerate().
I would favor readable code first, then using xrange() if available (i.e., Pre-Python v 3.x), followed by range() and enumerate().
这篇关于范围(len(list))还是枚举(list)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:范围(len(list))还是枚举(list)?
基础教程推荐
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
