Ask Your Question
2

How to perform natural sorting on a Python list that includes paths?

asked 2022-06-13 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-07-29 20:00:00 +0000

scrum gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-13 11:00:00 +0000

Seen: 8 times

Last updated: Jul 29 '21