Created
February 8, 2018 12:43
-
-
Save jelmervdl/d7319b4139aae7fc708bb7b101039126 to your computer and use it in GitHub Desktop.
Natural sorting in python (i.e. treat numbers as numbers)
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
items = [ | |
'a.5.b.1', | |
'a.1.b.4', | |
'a.1.b.14', | |
] | |
def natcast(item): | |
if item.isdigit(): | |
return int(item) | |
else: | |
return item | |
def natkey(item): | |
return tuple(natcast(item) for item in item.split('.')) | |
print(sorted(items, key=natkey)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment