To perform natural sorting on a Python list that includes paths, you can use the natsort
library.
First, install the natsort
library using pip:
pip install natsort
Then import the natsorted
function from the natsort
library and use it to sort the list:
from natsort import natsorted paths = [ "/path/to/folder_1", "/path/to/folder_10", "/path/to/folder_2", "/path/to/folder_20", "/path/to/folder_3" ] sorted_paths = natsorted(paths) print(sorted_paths)
Output:
['/path/to/folder_1', '/path/to/folder_2', '/path/to/folder_3', '/path/to/folder_10', '/path/to/folder_20']
As you can see, the paths are sorted naturally, which means that folder_10
and folder_20
come after folder_1
, folder_2
, and folder_3
.
Asked: 2022-06-13 11:00:00 +0000
Seen: 8 times
Last updated: Jul 29 '21