Sorting Multidimesional array(newbie)

Peter Otten __peter__ at web.de
Mon Dec 11 14:11:13 EST 2006


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 getitem
Traceback (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