Reputation: 2548
I have long list(nextWordIndices
) of indices size of 7000. I want to get value list from another list to mach that indices. I can do this but it take lots of time
nextWord = []
for i in nextWordIndices:
nextWord.append(allWords[i])
is there any optimize way?
Upvotes: 1
Views: 50
Reputation: 133634
Using a list comp:
nextWord = [allWords[i] for i in nextWordIndices]
Actually this might be faster (will have to timeit
)
map(allWords.__getitem__, nextWordIndices)
Upvotes: 1
Reputation: 310049
If the indices are frequently the same, you can use operator.itemgetter
:
word_getter = operator.itemgetter(*nextWordIndices)
nextWord = word_getter(allWords)
If you can use word_getter
multiple times, and tuple
s are OK for output, you might see a speed-up compared to a list-comprehension.
Timings:
python -m timeit -s "allWords = range(7000); nextWordIndices = range(7000)" "[allWords[i] for i in nextWordIndices]"
1000 loops, best of 3: 415 usec per loop
python -m timeit -s "allWords = range(7000); nextWordIndices = range(7000)" "map(allWords.__getitem__, nextWordIndices)"
1000 loops, best of 3: 614 usec per loop
python -m timeit -s "allWords = range(7000); nextWordIndices = range(7000); from operator import itemgetter" "itemgetter(*nextWordIndices)(allWords)"
1000 loops, best of 3: 292 usec per loop
Upvotes: 4
Reputation: 13985
Use map instead of loop.
def getWord(i):
return allWords[i]
nextWord = map(getWord, nextWordIndices)
Upvotes: 0