0 votes
1 view
in Python by (47.8k 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 (107k 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
1 answer
0 votes
2 answers
asked Jul 22, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...