Created
July 23, 2012 00:03
-
-
Save admackin/3161424 to your computer and use it in GitHub Desktop.
Python range filter - allows quick retrieval of keys within a given range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from blist import sorteddict, blist | |
class RangeFilter(sorteddict): | |
def filter_items(self, lt=None, lte=None, gt=None, gte=None): | |
"""Return the items with keys corresponding to the supplied parameters | |
('lt' denotes 'less than', 'gte' denotes 'greater than or equal' etc) | |
""" | |
bottom, top = self._get_range_indexes(lt, lte, gt, gte) | |
return self.items()[bottom:top] | |
def filter_values(self, lt=None, lte=None, gt=None, gte=None): | |
"""Return the values with keys corresponding to the supplied parameters | |
('lt' denotes 'less than', 'gte' denotes 'greater than or equal' etc) | |
""" | |
bottom, top = self._get_range_indexes(lt, lte, gt, gte) | |
return self.values()[bottom:top] | |
def filter_keys(self, lt=None, lte=None, gt=None, gte=None): | |
"""Return the keys corresponding to the supplied parameters | |
('lt' denotes 'less than', 'gte' denotes 'greater than or equal' etc) | |
""" | |
bottom, top = self._get_range_indexes(lt, lte, gt, gte) | |
return self.keys()[bottom:top] | |
def _get_range_indexes(self, lt=None, lte=None, gt=None, gte=None): | |
bottom = 0 | |
keys = self.keys() | |
top = len(keys) - 1 | |
if gte is not None: | |
bottom = keys.bisect_left(gte) | |
if gt is not None: | |
bottom = keys.bisect_right(gt) | |
if lte is not None: | |
top = keys.bisect_right(lte) | |
if lt is not None: | |
top = keys.bisect_left(lt) | |
return bottom, top |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment