Skip to content

Instantly share code, notes, and snippets.

@chris-kuhr
Forked from yuchen-xue/sorted_alphanumeric.py
Created February 19, 2023 20:28
Show Gist options
  • Select an option

  • Save chris-kuhr/8e6b11efd9a3b5464303859261346570 to your computer and use it in GitHub Desktop.

Select an option

Save chris-kuhr/8e6b11efd9a3b5464303859261346570 to your computer and use it in GitHub Desktop.
Python list sort alphanumerically.
"""
Since os.listdir returns filenames in an arbitary order,
this function is very handy for generating well-ordered filenames list.
Credit: https://stackoverflow.com/questions/4813061/non-alphanumeric-list-order-from-os-listdir/48030307#48030307
"""
import re
def sorted_alphanumeric(data):
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(data, key=alphanum_key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment