Sorting a list to by another's order

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Aug 30 10:07:52 EDT 2002


Graeme Longman <glongman at ilangua.com> wrote in 
news:mailman.1030713827.13913.python-list at python.org:

> Hi,
> 
> 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 ?

How about this?

>>> import sys
>>> listA = ['d', 'c', 'f', 'a', 'b', 'e']
>>> listB = ['a', 'c', 'd', 'f']
>>> 
>>> def ordering(aVal, bList):
	try:
		return bList.index(aVal), aVal
	except:
		return sys.maxint, aVal

	
>>> tmp = [ ordering(v, listB) for v in listA ]
>>> tmp.sort()
>>> listA = [ v for (i, v) in tmp ]
>>> print listA
['a', 'c', 'd', 'f', 'b', 'e']
>>> 


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list