from collections import OrderedDict
这样?
修改:
from bisect import insort
import numpy as np
class SortedDict():
def __init__(self, init_dict=None):
if init_dict:
self._dict = init_dict
self.keys = init_dict.keys()
self.key_set = set(self.keys)
else:
self._dict = dict()
self.keys = list()
self.key_set = set()
def add(self, key, value):
self._dict[key] = value
if key not in self.key_set:
insort(self.keys, key)
self.key_set.add(key)
def __getitem__(self, key):
return self._dict[key]
def full_dict(self):
return self._dict
def get_top_results(self, top_num):
tmp_key_list = np.array(self.keys[:top_num])
return map(lambda i: (i, self._dict[i]), tmp_key_list)
# Demo
test_dict = SortedDict()
test_dict.add(1, 1)
test_dict.add(1, 1)
test_dict.add(2, 1)
test_dict.add(3, 1)
test_dict.add(29, 1)
test_dict.add(346, 1)
test_dict.add(6, 1)
test_dict.add(9, 1)
result = list(test_dict.get_top_results(6))
print(result)
# Output: [(1, 1), (2, 1), (3, 1), (6, 1), (9, 1), (29, 1)]
你想实现的东西在上面了,不过复杂度奇高...
真的追求复杂度低的话,楼下的答案其实是正解。你有一个误区就是Python list的Access是O(n) 复杂度。但实际上常数复杂度。
https://wiki.python.org/moin/...