Created
December 18, 2012 11:40
-
-
Save anonymous/4327307 to your computer and use it in GitHub Desktop.
Group by ranges in Python
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
import itertools | |
def group_ranges(values, ranges): | |
# Utilities | |
split_at = lambda f: lambda l: \ | |
(itertools.takewhile(lambda e: not f(e), l), itertools.dropwhile(lambda e: not f(e), l)) | |
# Reducer | |
def f((values, acc), delim): | |
(pre, post) = split_at(lambda e: e >= delim)(values) | |
return (list(post), acc + [list(pre)]) | |
# Evaluation | |
(leftovers, groups) = reduce(f, ranges, (sorted(values), [])) | |
return groups + [leftovers] | |
# Demo | |
test_data = range(0, 15) | |
test_ranges = [2, 5, 9] | |
# Think ranges = [(0, 2), (2, 5), (5, 9)] | |
print group_ranges(test_data, test_ranges) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment