Fast sorting many lists together...?

Alex Martelli aleaxit at yahoo.com
Fri Sep 15 16:35:41 EDT 2000


"William Park" <parkw at better.net> wrote in message
news:20000915134034.B2932 at better.net...
> Hi,
>
> I need to sort about 50 lists (each about 500 elements) together, using
few
> of them as keys.  That is, sort the key lists first; look at which indexes
> have changed; then, shuffle the rest of list to reflect this new order.
>
> Does anyone know a fast fast routine for doing this?

If I understand you correctly, what you want is very well offered
by Numerical Python (which is not only for numerical stuff: its
arrays can hold generic Python objects).  If you do need to have
your stuff in lists, then moving it back and forth list<->array
might be slow, though.

So, as mentioned on another thread (yesterday, I think): zip
the list your sorting with the indices, then use those.  It's easier
in Python 2.0, currently in beta:

def sortone_changemany(firstlist, *theothers):
    zipped = zip(firstlist, range(len(firstlist)))
    zipped.sort()
    results = [ [i for i, j in zipped] ]
    indices = [j for i, j in zipped]
    for alist in theothers:
        results.append([alist[j] for j in indices])
    return results

With older Pythons, you can use map instead of zip, and more
explicit loops instead of the list comprehensions, but the
general idea is similar.


Alex






More information about the Python-list mailing list