Created
October 9, 2018 09:17
-
-
Save absentm/d4a6a56a0d60a735ade684ec76e1dd8e to your computer and use it in GitHub Desktop.
Natural sort of a string list
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
import re | |
def natural_sort(l): | |
convert = lambda text: int(text) if text.isdigit() else text.lower() | |
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] | |
return sorted(l, key = alphanum_key) | |
# use | |
natural_sort(ll) | |
################################################################################### | |
import re | |
def natural_key(string_): | |
"""See http://www.codinghorror.com/blog/archives/001018.html""" | |
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)] | |
def natural_sort(str_list): | |
return sorted(str_list, key=natural_key) | |
# use | |
natural_sort(ll) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment