Sorting by item_in_another_list
Cameron Walsh
cameron.walsh at gmail.com
Tue Oct 24 03:35:39 EDT 2006
Delaney, Timothy (Tim) wrote:
> Cameron Walsh wrote:
>
>> Hi,
>>
>> I have two lists, A and B, such that B is a subset of A.
>>
>> I wish to sort A such that the elements in B are at the beginning of
>> A, and keep the existing order otherwise, i.e. stable sort. The
>> order of elements in B will always be correct.
>>
>> for example:
>>
>> A = [0,1,2,3,4,5,6,7,8,9,10]
>> B = [2,3,7,8]
>>
>> desired_result = [2,3,7,8,0,1,4,5,6,9,10]
>
> c = set(B)
> a.sort(key=c.__contains__, reverse=True)
>
> Tim Delaney
Depressingly simple. I like it.
More information about the Python-list
mailing list