a query on sorting

Satya Upadhya satyaupadhya at yahoo.co.in
Wed Sep 27 11:20:30 CEST 2006


Dear Friends,
I am having a few issues with respect to sorting using python. I am using
Python 2.4.3 Win32 (IDLE 1.1.3).

>>> x = [2,6,4]
>>> x.sort()
>>> x
[2, 4, 6]
>>> x = [2,6,4]
>>> y = []
>>> y = x.sort()
>>> y
>>> print y
None

So the problem essentially is that i am unable to store the sorted
elements of list x into an empty list y in a straightforward manner. I can
get around this, of course, using the following:
>>> x = [2,6,4]
>>> x.sort()
>>> x
[2, 4, 6]
>>> y = []
>>> for i in x:
        y.append(i)


>>> y
[2, 4, 6]

But this seems a little less succinct then one would expect from python.

Also, consider the sorting of the indices of a sorted list. Consider the
following code:
>>> x = [2,6,4]
>>> import operator
>>> sortedindices = sorted(range(len(x)), key = x.__getitem__)
>>> print sortedindices
[0, 2, 1]
>>> x.sort()
>>> x
[2, 4, 6]
>>>

x (x = [2,6,4] originally) is the original list, and its indices are
0,1,2. If you sort x, then x becomes [2,4,6] and the the list of the
sorted indices becomes [0,2,1] since the 4 (which originally corresponds
to index 2) has now shifted to a position corresponding to index 1 and
likewise for element 6.

The equivalent matlab code for getting the sorted indices is much simpler:
if x is a list (array) of values, then just write:

[y,i] = sort(x);
and y will be a list containing the sorted elements of x and i will be a
list containing the sorted indices.

Am i missing a trick here?

Thanking you,
Satya


 				
---------------------------------
 Find out what India is talking about on  - Yahoo! Answers India 
 Send FREE SMS to your friend's mobile from Yahoo! Messenger Version 8. Get it NOW
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20060927/bbee66de/attachment.html>


More information about the Python-list mailing list