鉴于 Python在未实现b.__gt__(a)
时尝试,a.__lt__(b)
您不需要更改日志条目的类,提供足够智能的密钥就足够了:
import bisect
from functools import total_ordering
from operator import itemgetter
log = [
{'time': 199920331000, 'message': 'message1'},
{'time': 199920331001, 'message': 'message2'},
# ...
]
@total_ordering
class Key(object):
def __init__(self, keyfunc, keyval):
self.keyfunc = keyfunc
self.keyval = keyval
def __eq__(self, other):
return self.keyval == self.keyfunc(other)
def __lt__(self, other):
return self.keyval < self.keyfunc(other)
start = bisect.bisect(log, Key(itemgetter("time"), 199920331000))
print log[start:]
或者,您可以围绕 dicts 列表包装视图:
def keyed(items, key):
class View(object):
def __getitem__(self, index):
return key(items[index])
def __len__(self):
return len(items)
return View()
start = bisect.bisect(keyed(log, itemgetter("time")), 199920331000)
print log[start:]
(这是从删除元组的智能方式中剥离出来的)