Sorting Multidimesional array(newbie)

Brian Mills HardToSpell at gmail.com
Thu Dec 14 02:57:11 EST 2006


Fredrik Lundh wrote:

> 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])

Good point.

> 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

Is this mostly because of the stability problem described here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234 ?  Or is
it more a performance issue due having to make so many function calls?
>
> 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...

I can't believe I didn't try this, but for the given example it works
perfectly.  It even acts gracefully when you give it such sociopathic
lists as

>>> c = [[3, 1], [8, 2], [6, 3], [12, 4], [1, 5], ["oh noes!", 6], [24, 7], [ope
n("file.txt", 'r'), 8], [[1, 2, 3], 9]]
>>> c.sort()
>>> c
[[1, 5], [3, 1], [6, 3], [8, 2], [12, 4], [24, 7], [<open file
'file.txt', mode
'r' at 0x00A65608>, 8], [[1, 2, 3], 9], ['oh noes!', 6]]

Though changing the ordering system it decides to use may take some
more research.




More information about the Python-list mailing list