[Tutor] Sorting against another list
Roeland Rengelink
r.b.rigilink@chello.nl
Fri, 22 Jun 2001 08:44:37 +0200
Sharriff Aina wrote:
>
> Hi!
>
> I have a list that is created dynamically, how do I sort this list so that
> it matches amother "mater template" list?
>
> example:
> [ 'aa', 'qq', 'ttt', 'hh'] # master list
>
> my dynamic list cotains all or only a few of the elements in the master
> list:
>
> ['ttt', 'hh', 'aa'] ### i would like to sort it to produce ['aa''ttt',
> 'hh'] accoriding to the sequense in the master list
>
> or [ 'hh', 'qq' 'ttt'] ### would like ['qq', 'ttt', 'hh']
>
> I would like to sort these example list so that they at least follow the
> order of the master list.
>
> Thanks for any ideas
>
> Sharriff
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
You can do a sort on a list with a custom comparison function
alist.sort(cmp_func)
The master list defines an order for it's elements, we can use this to
build a comparison function. Something like:
ordered_list = [ 'aa', 'qq', 'ttt', 'hh']
def cmp_func(a, b):
'''A function returning
-1 if a<b, 0 if a == b 1 if a>b
ordering is based on the index of a and b in the global
'ordered_list'
if a or b not in ordered_list, a ValueError is raised'''
ord = ordered_list.index(a)-ordered_list.index(b)
if ord < 0:
return -1
if ord > 0:
return 1
return 0
my_list = [ 'hh', 'qq', 'ttt']
my_list.sort(cmp_func)
print mylist
will result in
['qq', 'ttt', 'hh']
Hope this helps.
Roeland
--
r.b.rigilink@chello.nl
"Half of what I say is nonsense. Unfortunately I don't know which half"