sort one list using the values from another list
Jeffrey Schwab
jeff at schwabcenter.com
Sun Feb 26 11:31:19 EST 2006
Brian Blais wrote:
> Hello,
>
> I have two lists, one with strings (filenames, actually), and one with a
> real-number
> rank, like:
>
> A=['hello','there','this','that']
> B=[3,4,2,5]
>
> I'd like to sort list A using the values from B, so the result would be
> in this example,
>
> A=['this','hello','there','that']
>
> The sort method on lists does in-place sorting. Is there a way to do
> what I want here?
If A has no duplicate elements, you could create a hash mapping A's
elements to their respective precedences, then provide a sort criterion
that accessed the hash. Alternatively, you could do something like this:
from operator import itemgetter
result = map(itemgetter(0), sorted(zip(A, B), key=itemgetter(1)))
More information about the Python-list
mailing list