Sorting by item_in_another_list

Paul McGuire ptmcg at austin.rr._bogus_.com
Tue Oct 24 00:19:50 EDT 2006


"Cameron Walsh" <cameron.walsh at gmail.com> wrote in message 
news:ehk3p8$j3q$1 at enyo.uwa.edu.au...
> 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?
>

Think in Python.  Define a function to take the list, and have that function 
return the proper comparison function.  This gives me the chance to also 
convert the input list to a set, which will help in scaling up my list to 
hundreds of elements.  See below.

-- Paul


def sort_by_in_list(reflist):
    reflist = set(reflist)
    def sort_by_in_list_(x,y):
        ret = 0
        if x in reflist: ret -= 1
        if y in reflist: ret += 1
        return ret
    return sort_by_in_list_

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

Gives:
[2, 3, 7, 8, 0, 1, 4, 5, 6, 9, 10]





More information about the Python-list mailing list