Python的每个比索引更快?

Cam*_*art 0 python for-loop

在 python 中,哪个更快?

1

for word in listOfWords:
    doSomethingToWord(word)
Run Code Online (Sandbox Code Playgroud)

2

for i in range(len(listOfWords)):
    doSomethingToWord(listOfWords[i])
Run Code Online (Sandbox Code Playgroud)

当然,我会在 python 2.x 中使用 xrange。

我的假设是 1. 比 2 快。如果是这样,为什么呢?

Dun*_*can 5

使用Python的timeit模块来回答此类问题:

duncan@ubuntu:~$ python -m timeit -s "listOfWords=['hello']*1000" "for word in listOfWords: len(word)"
10000 loops, best of 3: 37.2 usec per loop
duncan@ubuntu:~$ python -m timeit -s "listOfWords=['hello']*1000" "for i in range(len(listOfWords)): len(listOfWords[i])"
10000 loops, best of 3: 52.1 usec per loop
Run Code Online (Sandbox Code Playgroud)