Created
October 13, 2014 23:54
-
-
Save offby1/9f902c037edc536fe7a8 to your computer and use it in GitHub Desktop.
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
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