Skip to content

Instantly share code, notes, and snippets.

@carlos-jenkins
Created January 17, 2019 21:36
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 carlos-jenkins/c0d59a3e0d9034b946f40ac1aff29264 to your computer and use it in GitHub Desktop.
Save carlos-jenkins/c0d59a3e0d9034b946f40ac1aff29264 to your computer and use it in GitHub Desktop.
Sorters
def naturalsorted(iterable):
"""
Sort given iterable of strings using the "natural sorter" algorithm.
:param iterable: An iterable that yield strings.
:return: A list of elements in iterable naturally sorted.
:rtype: list
"""
from re import split
def convert(text):
return int(text) if text.isdigit() else text.lower()
def alphanum_key(key):
return [convert(c) for c in split('([0-9]+)', key)]
return sorted(iterable, key=alphanum_key)
def criteriasorted(criteria, unknowns_sorter=sorted):
"""
Sort a list using the given criteria (order of elements).
Also allows unknown elements that will be sorted using the unknowns_sorter
after the criteria.
:param list criteria: User defined order of elements.
:param function unknowns_sorter: Sorter to sort the unknown elements not
found in criteria.
:return: A sorter function.
:rtype: function
"""
def sorter(iterable):
criteria_set = set(criteria)
elements_set = set(iterable)
known = elements_set & criteria_set
unknown = elements_set - criteria_set
return sorted(known, key=criteria.index) + sorted(unknown)
return sorter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment