Sorting Multidimesional array(newbie)

Fredrik Lundh fredrik at pythonware.com
Tue Dec 12 02:38:30 EST 2006


Brian Mills wrote:

> There's another (IMHO more readable) way to do it if you can afford
> defining a short little "compare" function, and telling <list>.sort()
> to use that instead of its default:
> 
>>>> def myListCmp(lst1, lst2):
> ...   if lst1[0] < lst2[0]: return -1
> ...   if lst2[0] > lst2[0]: return 1
> ...   return 0

shorter:

	def myListCmp(a, b):
	    return cmp(a[0], b[0])

but using a compare function instead of a key mapper is not good advice, 
in general.  brief discussion here:

http://effbot.org/pyfaq/i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python

also note the OP didn't specify what to do for records where the first 
column was identical, so I guess a plain sort() call, without any custom 
compares or mappings, would work as well as the fancier alternatives...

</F>




More information about the Python-list mailing list