Home > Backend Development > Python Tutorial > How Does Python's `natsort` Library Achieve Natural Sorting?

How Does Python's `natsort` Library Achieve Natural Sorting?

Patricia Arquette
Release: 2024-12-28 18:09:10
Original
757 people have browsed it

How Does Python's `natsort` Library Achieve Natural Sorting?

Natural Sorting in Python

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.

Natural Sorting with natsort

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())
Copy after login

This will sort the list according to natural ordering ('elm0', 'elm1', etc.).

Sorting Key with natsort_keygen

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)
Copy after login

This will sort the list in the same natural order.

Special Case: Sorting like Windows Explorer

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template