[Tutor] which is better solution of the question

Lie Ryan lie.1296 at gmail.com
Tue Jun 16 19:40:25 CEST 2009


Abhishek Tiwari wrote:
> *Question :*
> The first list contains some items, and the second list contains their
> value (higher is better).
>  
> items = [apple, car, town, phone]
> values = [5, 2, 7, 1]
>  
> Show how to sort the 'items' list based on the 'values' list so that you
> end up with the following two lists:
>  
> items = [town, apple, car, phone]
> values = [7, 5, 2, 1]
>  
> *Ans. 1*
>  
> values, items = list(zip(*sorted(zip(values,items), reverse=True)))
>  
> *Ans. 2*
> new_values = sorted(values, reverse=True)
> new_items = [items[x] for x in map(values.index,new_values)]
>  
>  
> I would like to know which method is better and why?

Don't know about being better, but this is another alternative:
>>> keygen = iter(values)
>>> sorted(items, key=lambda x: next(keygen), reverse=True)

I'm thinking that maybe sorted/sort should accept a keylist= argument
that takes a list/tuple/iterable of keys, so we can write it like this:

>>> sorted(items, keylist=values, reverse=True)

what do you think?



More information about the Tutor mailing list