Sorting a list by another's order

Graeme Longman glongman at ilangua.com
Fri Aug 30 10:11:56 EDT 2002


Thanks - very nice.

Would it be much trickier if the list that needs sorting is a list of tuples
and I need to sort it by the first item of each tuple ?

Cheers,
Graeme

Mark McEahern wrote:

> [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
>
> -
>
> --
> http://mail.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list