Created
September 5, 2014 12:32
-
-
Save mbarkhau/b27304ff21f60b2653f5 to your computer and use it in GitHub Desktop.
Sort items in a list by multiple fields
This file contains 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 operator import itemgetter | |
def multisort(vals, sort_spec, in_place=False): | |
comparers = [] | |
for i, spec in enumerate(sort_spec): | |
if isinstance(spec, tuple): | |
key, polarity = spec | |
elif isinstance(spec, (str, unicode)): | |
key = spec.replace("-", "", 1) | |
polarity = 1 | |
if spec[0] == "-": | |
polarity = -1 | |
else: | |
key = i | |
polarity = spec | |
if callable(key): | |
key_fn = key | |
else: | |
key_fn = itemgetter(key) | |
comparers.append((key_fn, polarity)) | |
def _compare_fn(left, right): | |
for func, polarity in comparers: | |
result = cmp(func(left), func(right)) * polarity | |
if result: | |
return result | |
return 0 | |
if in_place: | |
vals.sort(cmp=_compare_fn) | |
return vals | |
return sorted(vals, _compare_fn) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment