a query on sorting

Steve Holden steve at holdenweb.com
Wed Sep 27 07:51:02 EDT 2006


Satya Upadhya wrote:
> 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.
> 
Not only that, but you've also modified the original list, which seems 
to conflict with your requirements.

> 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 indice
>  s 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
> 
  >>> sorted
<built-in function sorted>
  >>> a = [9,4,3,5,2,6,7,1,2]
  >>> b = sorted(a)
  >>> a
[9, 4, 3, 5, 2, 6, 7, 1, 2]
  >>> b
[1, 2, 2, 3, 4, 5, 6, 7, 9]
  >>>

Remember that sort() was specifically designed top operate on a list 
in-place, so it always returns None.

If you want the indexes as well you need to become a bit tricky. 
Remember that enumerate() will produced two-element tuples with the 
index value associated with the list value.

  >>> [x for x in enumerate(a)]
[(0, 9), (1, 4), (2, 3), (3, 5), (4, 2), (5, 6), (6, 7), (7, 1), (8, 2)]

But you really want the index second, so the sort works on the list 
values not the index values. Combining all this we get

  >>> sorted((x[1], x[0]) for x in enumerate(a))
[(1, 7), (2, 4), (2, 8), (3, 2), (4, 1), (5, 3), (6, 5), (7, 6), (9, 0)]

Tadaaa!

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list