Sorting Multidimesional array(newbie)

Brian Mills HardToSpell at gmail.com
Tue Dec 12 02:11:03 EST 2006


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
...
>>> a = [[5, 2], [1, 3]]
>>> a
[[5, 2], [1, 3]]
>>> a.sort(cmp=myListCmp)
>>> a
[[1, 3], [5, 2]]
>>>

On Dec 11, 11:11 am, Peter Otten <__pete... at web.de> wrote:
> Matimus wrote:
> > Tartifola wrote:
> >> Hi,
> >> how can I sort an array like
>
> >> array([[5, 2],
> >>        [1, 3]])
>
> >> along the first column to obtain
>
> >> array([[1, 3],
> >>        [5, 2]])
> >> i.e. keeping track of the ordered couples?
>
> >> Thanks,
> >> A
>
> > use a sort key:
>
> >>>>from operators import getitem
> >>>>a = [[5,2],[1,3]]
> >>>>a
> > [[5, 2], [1, 3]]
> >>>>a.sort(key=lambda x:getitem(x,0))
> >>>>a
> > [[1, 3], [5, 2]]Is that a faked session?
>
> >>> from operators import getitemTraceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ImportError: No module named operators
>
> >>> from operator import itemgetter
> >>> a = [[5, 2], [1, 3]]
> >>> a.sort(key=itemgetter(0))
> >>> a[[1, 3], [5, 2]]
> 
> Peter




More information about the Python-list mailing list