简体   繁体   中英

sorting a list with accent using sorted() function

I am trying to sort a list of strings using the sorted() function. The problem is that I am using (french) accent. I have tried:

import locale
import functools

locale.setlocale(locale.LC_ALL, 'fr_FR')
test=('pêche','pomme')
sortedtest=sorted(test,key=functools.cmp_to_key(locale.strcoll))

But it doesn't work (returns 'pomme, pêche' instead of 'pêche, pomme'). Could anyone help me?

I've run a few tests for you. I mean that as a comment but it doesn't fit into a comment so I must send it as an answer.

In [1]: import locale 
   ...: import functools 
   ...:  
   ...: locale.setlocale(locale.LC_ALL, 'fr_FR') 
   ...: test=('pêche','pomme') 
   ...: sorted(test,key=functools.cmp_to_key(locale.strcoll))                                                                                                                                      
Out[1]: ['pêche', 'pomme']

In [2]: import locale 
   ...: import functools 
   ...:  
   ...: locale.setlocale(locale.LC_ALL, 'fr_FR.utf8') 
   ...: test=('pêche','pomme') 
   ...: sorted(test,key=functools.cmp_to_key(locale.strcoll))                                                                                                                                      
Out[2]: ['pêche', 'pomme']

In [3]: import locale 
   ...: import functools 
   ...:  
   ...: locale.setlocale(locale.LC_ALL, 'fr_FR.ISO-8859-1') 
   ...: test=('pêche','pomme') 
   ...: sorted(test,key=functools.cmp_to_key(locale.strcoll))                                                                                                                                      
Out[3]: ['pêche', 'pomme']

In [4]: import locale 
   ...: import functools 
   ...:  
   ...: locale.setlocale(locale.LC_ALL, 'en_GB.ISO-8859-1') 
   ...: test=('pêche','pomme') 
   ...: sorted(test,key=functools.cmp_to_key(locale.strcoll))                                                                                                                                      
Out[4]: ['pêche', 'pomme']

Until now I could not get a result with returning 'pomme, pêche' instead of 'pêche, pomme'. I always get it in the order as you would like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM