Sorting a list to by another's order

Mark McEahern marklists at mceahern.com
Fri Aug 30 09:42:48 EDT 2002


[Graeme Longman]
> I have two lists:
> 
> listA = ['d', 'c', 'f', 'a', 'b', 'e']
> listB = ['a', 'c', 'd', 'f']
> 
> I need to sort listA so that it's order corresponds to that of listB (if
> the item in listA isn't in listB then it should be at the end of the
> list)
> 
> Is there a quick way to do this using sort() instead of writng a bunch
> of for loops and if-else statements ?

This relies on nested scopes:

def make_sort_by_list(list_with_order):
    def sort_by_list(x, y):
        try:
            order_of_x = list_with_order.index(x)
            order_of_y = list_with_order.index(y)
            return cmp(order_of_x, order_of_y)
        except ValueError:
            # Not found--stick it at the end.
            return 1
    return sort_by_list

listA = ['d', 'c', 'f', 'a', 'b', 'e']
listB = ['a', 'c', 'd', 'f']

sort_by = make_sort_by_list(listB)

listA.sort(sort_by)
print listA
expectedOrder = ['a', 'c', 'd', 'f', 'b', 'e']
assert listA == expectedOrder

-





More information about the Python-list mailing list