Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting accented names that start either with lowercase or uppercase

I am looking to sort the following list which contains names written in different ways:

l=['André','Gerald','Nicole','François','Fraçois','andré']

The expected result is:

['André', 'andré', 'Fraçois', 'François' 'Gerald', 'Nicole']

However, I am could not obtain it. Until now, I have tried to do a double sorting with the sorted command:

l=sorted(sorted(l, key=str.casefold), key=unidecode.unidecode)

But my result is not quite what I am looking for:

['André', 'Fraçois', 'François', 'Gerald', 'Nicole', 'andré']

Do you guys know any other command that could bring me the correct sorting?

like image 573
felipesveiga Avatar asked Nov 20 '25 07:11

felipesveiga


1 Answers

This should work:

import unidecode
l = ['André','Gerald','Nicole','François','Fraçois','andré']

l = sorted(l, key=lambda s: unidecode.unidecode(s).lower())

Result:

['André', 'andré', 'Fraçois', 'François', 'Gerald', 'Nicole']

Python sort is stable, therefore a nested sort would actually work.

like image 52
JLam Avatar answered Nov 21 '25 19:11

JLam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!