我有一个 score 函数,我想根据它对列表进行排序。
通常,这很容易(只需 sorted(l, key=score)),但我需要在代码后面的分数,而 score 的计算量很大(所以我想避免得分两次)。
这是我当前的代码:
scores= map(score, l)
new_l= [el for i,el in sorted(enumerate(l), key=lambda (i,el): scores[i])]
这行得通,但有点困惑,而且可读性不是特别好。
实现此目标的最佳方法是什么?
请您参考如下方法:
functools.lru_cache可能在这里有用。如文档中所示:
Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.
只需将 lru_cache 添加到您的函数中:
@lru_cache(maxsize=32)
def score(i):
...
