Skip to content

Instantly share code, notes, and snippets.

@jelmervdl
Created February 8, 2018 12:43
Show Gist options
  • Save jelmervdl/d7319b4139aae7fc708bb7b101039126 to your computer and use it in GitHub Desktop.
Save jelmervdl/d7319b4139aae7fc708bb7b101039126 to your computer and use it in GitHub Desktop.
Natural sorting in python (i.e. treat numbers as numbers)
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