partial list sort

Alex Martelli aleax at aleax.it
Thu Oct 10 06:10:44 EDT 2002


jsaul wrote:

> Hi there,
> 
> I am looking for the proper way to sort a list range-wise. The
> scenario is as follows: I am reading a list of data elements
> triple-wise component A, B and C, then the next triple A, B, C and
> so on.  Each list element has a component identifier which takes
> the values "A", "B", or "C". What I want is to sort the components
> within each *triple*, but *not* the while list, so that I can
> assure an order of A-B-C no matter what the original order in the
> data was, which can as well be B-C-A or whatever.

I see you've received good suggestions already, but wanted to
suggest a completely different tack based on the Decorate -
Sort - Undecorate (DSU) approach instead -- needs to be
measured on your system and on representative data to check
performance, but seems a potentially interesting alternative.

> 
> Here is a simplified version of my script illustrating the
> problem:
> 
>     list=[ [1,'C'], [2,'B'], [3,'A'], [4,'C'], [5,'B'], [6,'A'] ]
>     print list
> 
>     def sort_components (list):
> def cmp_comp (data1, data2):
> if   data1[1] == data2[1]:  return  0
>             elif data1[1]  < data2[1]:  return -1
> return 1
>         print list
> list.sort(cmp_comp)
>         print list
> return
> 
>     for k in range(0, len(list), 3):
> # sort over ranges:
>         sort_components(list[k:k+3])
> 
>     print list

Here's my suggestion (untested):

def jsaulsort(alist):
    aux = [ (i%3, alist[i][1], alist[i]) for i in range(len(alist)) ]
    aux.sort()
    alist[:] = [ item[2] for item in aux ]

somelist=[ [1,'C'], [2,'B'], [3,'A'], [4,'C'], [5,'B'], [6,'A'] ]
print somelist
jsaulsort(somelist)
print somelist


Alex




More information about the Python-list mailing list