localizing a sort
Ricardo Aráoz
ricaraoz at gmail.com
Sun Sep 2 13:55:57 EDT 2007
Alex Martelli wrote:
> Ricardo Aráoz <ricaraoz at gmail.com> wrote:
>> Peter Otten wrote:
> ...
>>>>>>> print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y)))
>>>> aeiouàáäèéëìíïòóöùúü
>>> The lambda is superfluous. Just write cmp=locale.strcoll instead.
>> No it is not :
>>>>> print ''.join(sorted(a, cmp=locale.strcoll(x,y)))
>> Traceback (most recent call last):
>> File "<input>", line 1, in <module>
>> TypeError: strcoll expected 2 arguments, got 0
>>
>> You need the lambda to assign both arguments.
>
> No, your mistake is that you're CALLING locale.strcoll, while as Peter
> suggested you should just PASS it as the cmp argument. I.e.,
>
> ''.join(sorted('ciao', cmp=locale.strcoll))
>
> Using key=locale.strxfrm should be faster (at least when you're sorting
> long-enough lists of strings), which is why strxfrm (and key=...:-)
> exist in the first place, but cmp=locale.strcoll, while usually slower,
> is entirely correct. That lambda _IS_ superfluous, as Peter said.
>
>
> Alex
Got it! And it is MUCH more elegant than my code. Thanks.
More information about the Python-list
mailing list