Need customised sort

Andrew Dalke dalke at dalkescientific.com
Sat Apr 13 21:32:00 EDT 2002


bvdpoel at uniserve.com:
>I have a list like this:
>

(from elsewhere)
> [ [0,x], [0,y], [4,n]...]. ...]

>and I want to sort it a bit. The sort should only work on the first
>element AND, retain the order of list elements if 2 adjacent elements
>have identical first elements.

suppose you have a list 'x' containing a set of terms

  x = [ [0, 5], [0, 4], [4, 1]]

then you could get the sort you wanted by

>>> y = [(term[0], i, term) for i, term in zip(range(len(x)), x)]
>>> y
[(0, 0, [0, 5]), (0, 1, [0, 4]), (4, 2, [4, 1])]
>>> y.sort()
>>> [term[2] for term in y]
[[0, 5], [0, 4], [4, 1]]
>>>

What this does is make a new list 'y' where each term in y is:
  - the first field from each term in x, which is the primary sort value

  - the index of the term, as in 0, 1, 2, 3, ..., which is the secondary
      sort value, used to reserve the original order if there are ties in
      the first sort value

  - the original term in x ; note, because the secondary sort keys are
      unique this value will never affect the sorting

This new list, 'y', is easily sorted by Python, and the result is in
the sort order you want.  You just need to get the original data out
of the list, by getting the 3rd term (the [2] term) from y.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list