Skip to content

Instantly share code, notes, and snippets.

@mbarkhau
Created September 5, 2014 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbarkhau/b27304ff21f60b2653f5 to your computer and use it in GitHub Desktop.
Save mbarkhau/b27304ff21f60b2653f5 to your computer and use it in GitHub Desktop.
Sort items in a list by multiple fields
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