Skip to content

Instantly share code, notes, and snippets.

@offby1
Created October 13, 2014 23:54
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 offby1/9f902c037edc536fe7a8 to your computer and use it in GitHub Desktop.
Save offby1/9f902c037edc536fe7a8 to your computer and use it in GitHub Desktop.
def sorted_alphanumerically(strings, key=None):
"""Sort alphabetically, except treat strings of digits as numbers.
If key is not None, it must return a string.
>>> sorted_alphanumerically(['r1', 'r10', 'r2'])
['r1', 'r2', 'r10']
>>> sorted_alphanumerically(['r1', 'R10', 'r2'])
['R10', 'r1', 'r2']
>>> sorted_alphanumerically(['r1', 'R10', 'r2'], key=str.lower)
['r1', 'r2', 'R10']
"""
if key is None:
key = lambda x: x
def split(s):
"""
>>> split('what has 18 legs and catches flies?')
['what has ', 18, ' legs and catches flies?']
"""
return [int(value) if index % 2 else value for index, value in enumerate(re.split(r'([0-9]+)', s))]
return sorted(strings, key=lambda elt: split(key(elt)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment