Possible Duplicate:
Only index needed: enumerate or (x)range?
哪些会被认为更好/更清晰/更快/更“Pythonic”?我不关心列表L
的内容,只关心它有多长。
a = [f(n) for n, _ in enumerate(L)]
或
a = [f(n) for n in range(len(L))]
如果有什么不同,f
函数也会使用 len(list)
。
最佳答案
一些快速的计时运行似乎使使用 range()
的第二个选项比 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)
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()
.
关于python - 范围(len(list))还是枚举(list)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11990105/