An ordering question

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Mar 13 22:34:52 EDT 2009


En Fri, 13 Mar 2009 17:33:51 -0200, Hrvoje Niksic <hniksic at xemacs.org>  
escribió:
> "andrew cooke" <andrew at acooke.org> writes:
>> Hrvoje Niksic wrote:
>>> Kottiyath <n.kottiyath at gmail.com> writes:
>>>
>>>>     I have 2 lists
>>>> a = [(4, 1), (7, 3), (3, 2), (2, 4)]
>>>> b = [2, 4, 1, 3]
>>>>     Now, I want to order _a_ (a[1]) based on _b_.
>>>>     i.e. the second element in tuple should be the same as b.
>>>>     i.e. Output would be [(3, 2), (2, 4), (4, 1), (7, 3)]
>>>
>>> a.sort(key=lambda (x, y): b[y - 1], reverse=True)
>>
>> that's hilarious!  i have no idea how it works
>
> Glad to have made someone laugh, but it in fact wasn't meant to.  :-)
> It was a combination of misunderstanding the question *and* trying out
> the answer.
>
> I understood that the second element of each tuple should be sorted
> according to the corresponding element in b.  This part is partly
> correct, but I took corresponding to mean that it should be sorted by
> the value of b[x], x being the second element of each tuple.  Since
> those elements appear to be 1-based, I added -1.  This produced a list
> in exactly the reverse order, so I added reverse=True.

This shows how important is to provide a good, unambiguous example in any  
specification. Not just a "correct" example, but one that also shows how  
things are not to be done. In case of doubt, people always look at the  
examples for clarification.

-- 
Gabriel Genellina




More information about the Python-list mailing list