If I understand you correctly, you are looking for the bisect
module, which implements an efficient algorithm for finding the point where a value in a sorted list is larger or smaller than a given value.
Your log entries need to be a class that implements some form of ordering though. Something like this:
from functools import total_ordering
@total_ordering
class LogEntry(object):
def __init__(self, time, message):
self.time = time
self.message = message
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.time == other.time and self.message == other.message
def __lt__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
if self.time == other.time:
return self.message < other.message
return self.time < other.time
These LogEntry
classes are orderable (with the help of the functools.total_ordering
class decorator), and thus the bisect
module knows what entries have a 'lower' value than other values.
Your function then becomes:
def getLog(timestamp):
dummy_entry = LogEntry(timestamp, '')
index = bisect.bisect_right(logs, dummy_entry)
return logs[index:]
Note that we don't need to declare logs
global as you are not assigning to it.