How do I sort these?

Bengt Richter bokr at oz.net
Sun Oct 30 17:36:47 EST 2005


On Sun, 30 Oct 2005 10:13:42 +0100, Peter Otten <__peter__ at web.de> wrote:

>Bengt Richter wrote:
>
[...]
>> Now select from the second list, by first-element position correspondence:
>>  >>> [second[t[1]] for t in sorted((f,i) for i,f in enumerate(first))]
>>  ['E', 'D', 'C', 'B', 'A', 'J', 'I', 'H', 'G', 'F']
>> 
>> Which did the OP really want? ;-)
>
>I don't know, but there certainly is no subtle requirement to not provide
>the key argument:
>
>>>> import operator
>>>> first = [2]*5 + [1]*5
>>>> second = list(reversed("ABCDEFGHIJ"))
>>>> [s for f, s in sorted(zip(first, second))]
>['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
>>>> [s for f, s in sorted(zip(first, second), key=operator.itemgetter(0))]
>['E', 'D', 'C', 'B', 'A', 'J', 'I', 'H', 'G', 'F']
>
D'oh yeah, forgot about key ;-/ (and this kind of problem probably at least
partly motivated its introduction, so it should have jumped to mind).
Thanks, your version is much cleaner ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list