An ordering question

MRAB google at mrabarnett.plus.com
Fri Mar 13 13:35:31 EDT 2009


MRAB wrote:
> Kottiyath wrote:
>> Hi,
>>     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)]
>>
>>     I did the same as follows:
>>>>> l = len(a) * [None]
>>>>> for (k, v) in a:
>> ...   for i, e in enumerate(b):
>> ...     if e == v:
>> ...        l[i] = (k, v)
>>
>>      This works, but the code -for python- looks very kludgy.
>>      I thought for ~2 hours to see whether I can do it in a line or 2,
>> but I cannot seem to find a mechanism.
>>      Can someone help me out?
>>
> How about:
> 
>  >>> a = [(4, 1), (7, 3), (3, 2), (2, 4)]
>  >>> b = [2, 4, 1, 3]
>  >>> d = dict((v, k) for k, v in a)
>  >>> c = [(d[s], s) for s in b]
>  >>> c
> [(3, 2), (2, 4), (4, 1), (7, 3)]
> 
> Understanding how it works is left as an exercise for the reader. :-)
> 
Actually, a more general solution is:

 >>> a = [(4, 1), (7, 3), (3, 2), (2, 4)]
 >>> b = [2, 4, 1, 3]
 >>> d = dict((t[1], t) for t in a)
 >>> c = [d[s] for s in b]
 >>> c
[(3, 2), (2, 4), (4, 1), (7, 3)]



More information about the Python-list mailing list