Darshana
Darshana

Reputation: 2548

optimized way to get values from list when list of indices given

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

Answers (3)

jamylak
jamylak

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

mgilson
mgilson

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 tuples 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

sarveshseri
sarveshseri

Reputation: 13985

Use map instead of loop.

def getWord(i):
    return allWords[i]

nextWord = map(getWord, nextWordIndices)

Upvotes: 0

Related Questions