In Python, the sorted() function sorts strings in ASCIIbetical order. However, for scenarios where a natural sort is desired, a library called natsort comes to the rescue.
natsort provides both a sorting function and a sorting key. For a sorting function, you can use natsorted():
from natsort import natsorted l = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] natsorted(l, key=lambda y: y.lower())
This will sort the list according to natural ordering ('elm0', 'elm1', etc.).
If a sorting key is more suitable, you can use natsort_keygen():
from natsort import natsort_keygen l = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] sort_key = natsort_keygen(key=lambda y: y.lower()) l.sort(key=sort_key)
This will sort the list in the same natural order.
natsort also provides the os_sorted function to sort in the same order as the file system browser on a particular operating system:
from natsort import os_sorted paths = ['path/to/file1', 'path/to/file10', 'path/to/file2'] os_sorted(paths)
This will sort the paths according to the operating system's file explorer.
The above is the detailed content of How Does Python's `natsort` Library Achieve Natural Sorting?. For more information, please follow other related articles on the PHP Chinese website!