Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort.

Natural sort: The order by which files in Windows are sorted.

For instance, the following list is naturally sorted (what I want):

['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']

And here's the "sorted" version of the above list (what I have):

['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']

I'm looking for a sort function which behaves like the first one.

1 Answer

0 votes
by (106k points)

You can use the below-mentioned code:

import re 

def natural_sort(l): 

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(l, key = alphanum_key)

Output:

['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
4 answers
asked Apr 18, 2021 in Python by laddulakshana (16.4k points)
0 votes
2 answers
asked Jul 22, 2019 in Python by Sammy (47.6k points)
0 votes
4 answers

Browse Categories

...