我有一个索引大小为7000的长列表(nextWordIndices
)。我想从另一个列表中获取值列表来处理该索引。我可以做到,但是要花很多时间
nextWord = []
for i in nextWordIndices:
nextWord.append(allWords[i])
有什么优化方法吗?
最佳答案
如果索引经常相同,则可以使用operator.itemgetter
:
word_getter = operator.itemgetter(*nextWordIndices)
nextWord = word_getter(allWords)
如果可以多次使用
word_getter
,并且tuple
可以输出,则与列表理解相比,您可能会看到速度有所提高。时间:
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