问题描述
我正在尝试使用 sorted() 函数对字符串列表进行排序。问题是我正在使用(法语)口音。我试过了:
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))
但它不起作用(返回 'pomme,pêche' 而不是 'pêche,pomme')。有人可以帮我吗?
解决方法
我已经为您进行了一些测试。我的意思是作为评论但它不适合评论所以我必须将其作为答案发送。
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',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',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',key=functools.cmp_to_key(locale.strcoll))
Out[4]: ['pêche','pomme']
到目前为止,我无法通过返回 'pomme,pêche' 而不是 'pêche,pomme' 得到结果。我总是按照你的顺序得到它。