Sorting by item_in_another_list

Cameron Walsh cameron.walsh at gmail.com
Tue Oct 24 06:19:35 CEST 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]
> 
> 
> At the moment I have defined a comparator function:
> 
> def sort_by_in_list(x,y):
>     ret = 0
>     if x in B:
>         ret -= 1
>     if y in B:
>         ret += 1
>     return ret
> 
> and am using:
> 
> A.sort(sort_by_in_list)
> 
> which does produce the desired results.
> 
> I do now have a few questions:
> 
> 1.)  Is this the most efficient method for up to around 500 elements? If 
> not, what would be better?
> 2.)  This current version does not allow me to choose a different list 
> for B.  Is there a bind_third function of some description that I could 
> use to define a new function with 3 parameters, feed it the third (the 
> list to sort by), and have the A.sort(sort_by_in_list) provide the other 
> 2 variables?
> 
> 
> Regards to all,
> 
> Cameron.


Well I found an answer to the second question with the following:

 >>> A=[0,1,2,3,4,5,6,7,8,9,10]
 >>> B=[2,3,7,8]
 >>> def sort_by_in_list(in_list):
	def ret_function(x,y):
		ret = 0
		if x in in_list:
			ret -= 1
		if y in in_list:
			ret += 1
		return ret
	return ret_function

 >>> A.sort(sort_by_in_list(B))
 >>> A
[2, 3, 7, 8, 0, 1, 4, 5, 6, 9, 10]


Hope it helps someone,

Cameron.



More information about the Python-list mailing list