Last active
October 24, 2022 04:21
-
-
Save korakot/6da3628a851846cde925ecf50aaaabef to your computer and use it in GitHub Desktop.
Natural Sort in python
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 | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use re.split('([0-9]+)', str(key)) if use with pathlib Path.