Sorting by item_in_another_list

Delaney, Timothy (Tim) tdelaney at avaya.com
Tue Oct 24 00:50:36 EDT 2006


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



More information about the Python-list mailing list