Created
July 25, 2015 16:46
-
-
Save offby1/9e3d27c754fe3ff02ba6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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'] | |
| See also http://nedbatchelder.com/blog/200712/human_sorting.html | |
| and https://pypi.python.org/pypi/natsort | |
| """ | |
| 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