Skip to content

Instantly share code, notes, and snippets.

@korakot
Last active October 24, 2022 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korakot/6da3628a851846cde925ecf50aaaabef to your computer and use it in GitHub Desktop.
Save korakot/6da3628a851846cde925ecf50aaaabef to your computer and use it in GitHub Desktop.
Natural Sort in python
import re
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
sorted(items, key=alphanum)
# another solution
natsort = lambda s: [int(t) if t.isdigit() else t.lower() for t in re.split('(\d+)', s)]
sorted(items, key=natsort)
@korakot
Copy link
Author

korakot commented Oct 24, 2022

Use re.split('([0-9]+)', str(key)) if use with pathlib Path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment