インデックス サイズが 7000 の長い list( nextWordIndices
) があります。別のリストから値リストを取得して、そのインデックスに対応させたいと考えています。できるけど時間がかかる
nextWord = []
for i in nextWordIndices:
nextWord.append(allWords[i])
最適化の方法はありますか?
インデックスが頻繁に同じである場合は、次を使用できますoperator.itemgetter
。
word_getter = operator.itemgetter(*nextWordIndices)
nextWord = word_getter(allWords)
word_getter
複数回使用でき、 tuple
s が出力に問題ない場合は、リスト内包表記と比較して速度が向上する可能性があります。
タイミング:
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
リストカンプの使用:
nextWord = [allWords[i] for i in nextWordIndices]
実際、これはより速いかもしれません(する必要がありますtimeit
)
map(allWords.__getitem__, nextWordIndices)
ループの代わりにマップを使用します。
def getWord(i):
return allWords[i]
nextWord = map(getWord, nextWordIndices)