What is faster for loop using enumerate or for loop using xrange in Python?

ⅰ亾dé卋堺 提交于 2019-12-01 19:38:56

问题


What is faster, a for loop using enumerate or using xrange?

EDIT: I have tested, and I just see minimal differences.


回答1:


Enumerate is slightly faster. Tested in Python 3:

>>>import pygame
>>>pygame.init()
>>>clock = pygame.time.Clock()
>>>a = list(range(100000))
>>>def do_with_range():
...    clock.tick()
...    k = 0
...    for i in range(len(a)):
...        k += a[i]
...    print(clock.tick())
>>>def do_with_enumerate():
...    clock.tick()
...    k = 0
...    for i, j in enumerate(a):
...        k += j
...    print(clock.tick())
>>>do_with_range()
23
>>>do_with_enumerate()
21

If a wouldn't be a list, but a generator, it would be significantly faster to use enumerate (74ms using range, 23ms using enumerate).




回答2:


You can use the timeit module in the standard library to compare both. The timeit.timeit() function used below takes a statement that it runs 1'000'000 times and returns the total time in seconds. In this test enumerate() is slightly slower.

>>> import timeit
>>> timeit.timeit('for i in xrange(100): a[i]', 'a = list(xrange(100))')
7.2920000553131104
>>> timeit.timeit('for i, o in enumerate(a): o', 'a = list(xrange(100))')
10.359999895095825
>>> timeit.timeit('for i in xrange(100): a[i] + 1', 'a = list(xrange(100))')
10.380000114440918
>>> timeit.timeit('for i, o in enumerate(a): o + 1', 'a = list(xrange(100))')
13.514999866485596



回答3:


Mu.

For loops can use both enumerate and xrange at the same time, though it would be silly. The enumerate function adds an index so you can tell what the index of an item in your iterable is. The xrange function returns an iterable full of numbers. Use it when you want to do something a certain number of times, instead of for each element in an iterable.

Examples:

for idx, element in ['foo', 'bar', 'baz']:
    print idx, element

for idx in xrange(3):
    print idx


来源:https://stackoverflow.com/questions/4852944/what-is-faster-for-loop-using-enumerate-or-for-loop-using-xrange-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!