005_014 Python 給字典型別增加排名功能
阿新 • • 發佈:2018-12-30
程式碼如下:
#encoding=utf-8 print '中國' #給字典型別增加排名功能 from bisect import bisect_left, insort_left import UserDict class Ratings(UserDict.DictMixin, dict): def __init__(self, *args, **kwds): dict.__init__(self, *args, **kwds) # self._rating is the crucial auxiliary data structure: a list # of all (value, key) pairs, kept in "natural"ly-sorted order self._rating = [ (v, k) for k, v in dict.iteritems(self) ] self._rating.sort( ) def copy(self): return Ratings(self) def __setitem__(self, k, v): if k in self: del self._rating[self.rating(k)] dict.__setitem__(self, k, v) insort_left(self._rating, (v, k)) def __delitem__(self, k): del self._rating[self.rating(k)] dict.__delitem__(self, k) __len__ = dict.__len__ __contains__ = dict.__contains__ has_key = __contains__ def __iter__(self): for v, k in self._rating: yield k iterkeys = __iter__ def keys(self): return list(self) def rating(self, key): item = self[key], key i = bisect_left(self._rating, item) if item == self._rating[i]: return i raise LookupError, "item not found in rating" def getValueByRating(self, rating): return self._rating[rating][0] def getKeyByRating(self, rating): return self._rating[rating][1] r = Ratings({"1": 2, "12": 123}) print [r.rating(key) for key in ["12", "12", "1"]]
列印結果如下:
中國
[1, 1, 0]