Problem with the sort() function

Nick Coghlan ncoghlan at iinet.net.au
Tue Feb 22 04:55:25 EST 2005


clementine wrote:
> Hi,
> 
> I have an array of arrays in the form of 
> list = [[3,'fork',0.3,1],[2,'fork,0.1,2],[3,'exec',0.2,2]]
> 
> The in-built sort(),list.sort() sorts on the first element, if the first
> elts are equal then it sorts on the second elt and so on...But i really
> dont want to search on the second elt if the first elts are equal...the
> 1-D lists shud be left in the same position i.e. i want the sorted list to
> be [[2,'fork',0.1,2],[3,'fork,0.3,1],[3,'exec',0.2,2]] and not
> [[2,'fork',0.1,2],[3,'exec',0.2,2],[3,'fork,0.3,1]].

Try this:

Py> from operator import itemgetter
Py> list = [[3,'fork',0.3,1],[2,'fork',0.1,2],[3,'exec',0.2,2]]
Py> list.sort(key=itemgetter(0))
Py> list
[[2, 'fork', 0.10000000000000001, 2], [3, 'fork', 0.29999999999999999, 1], [3, '
exec', 0.20000000000000001, 2]]

If the 'key' argument isn't accepted (i.e. you aren't using Python 2.4), you'll 
need to do the decoration manually:

def mysort(iterable, cmp=None, key=None, reverse=False):
     "return a sorted copy of its input"
     if sys.version_info >= (2,4):
         return sorted(iterable, cmp, key, reverse)
     seq = list(iterable)
     if reverse:
         seq.reverse()        # preserve stability
     if key is not None:
         seq = [(key(elem), i, elem) for i, elem in enumerate(seq)]
     seq.sort(cmp)
     if key is not None:
         seq = [elem for (key, i, elem) in seq]
     if reverse:
         seq.reverse()
     return seq

list = mysort([[3,'fork',0.3,1],[2,'fork',0.1,2],[3,'exec',0.2,2]],
                key=lambda x: x[0])

(Taken from Raymond's code in:
http://mail.python.org/pipermail/python-list/2005-January/263275.html)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list