我nextWordIndices
的索引大小为 7000 的长列表()。我想从另一个列表中获取值列表以匹配该索引。我可以做到,但需要很多时间
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)