<pre>Dear Friends,<br>I am having a few issues with respect to sorting using python. I am using<br>Python 2.4.3 Win32 (IDLE 1.1.3).<br><br><font color="#800000">>>> x = [2,6,4]</font><br><font color="#800000">>>> x.sort()</font><br><font color="#800000">>>> x</font><br>[2, 4, 6]<br><font color="#800000">>>> x = [2,6,4]</font><br><font color="#800000">>>> y = []</font><br><font color="#800000">>>> y = x.sort()</font><br><font color="#800000">>>> y</font><br><font color="#800000">>>> print y</font><br>None<br><br>So the problem essentially is that i am unable to store the sorted<br>elements of list x into an empty list y in a straightforward manner. I can<br>get around this, of course, using the following:<br><font color="#800000">>>> x = [2,6,4]</font><br><font color="#800000">>>> x.sort()</font><br><font color="#800000">>>> x</font><br>[2, 4, 6]<br><font
color="#800000">>>> y = []</font><br><font color="#800000">>>> for i in x:</font><br> y.append(i)<br><br><br><font color="#800000">>>> y</font><br>[2, 4, 6]<br><br>But this seems a little less succinct then one would expect from python.<br><br>Also, consider the sorting of the indices of a sorted list. Consider the<br>following code:<br><font color="#800000">>>> x = [2,6,4]</font><br><font color="#800000">>>> import operator</font><br><font color="#800000">>>> sortedindices = sorted(range(len(x)), key = x.__getitem__)</font><br><font color="#800000">>>> print sortedindices</font><br>[0, 2, 1]<br><font color="#800000">>>> x.sort()</font><br><font color="#800000">>>> x</font><br>[2, 4, 6]<br><font color="#800000">>>></font><br><br>x (x = [2,6,4] originally) is the original list, and its indices are<br>0,1,2. If you sort x, then x becomes [2,4,6] and the the list of the<br>sorted
indices becomes [0,2,1] since the 4 (which originally corresponds<br>to index 2) has now shifted to a position corresponding to index 1 and<br>likewise for element 6.<br><br>The equivalent matlab code for getting the sorted indices is much simpler:<br>if x is a list (array) of values, then just write:<br><br>[y,i] = sort(x);<br>and y will be a list containing the sorted elements of x and i will be a<br>list containing the sorted indices.<br><br>Am i missing a trick here?<br><br>Thanking you,<br>Satya<br></pre><p>
<hr size=1></hr>
Find out what India is talking about on - <a href="http://us.rd.yahoo.com/mail/in/yanswers/*http://in.answers.yahoo.com/">Yahoo! Answers India</a> <BR>
Send FREE SMS to your friend's mobile from Yahoo! Messenger Version 8. <a href="http://us.rd.yahoo.com/mail/in/messengertagline/*http://in.messenger.yahoo.com">Get it NOW</a>