sort one list using the values from another list

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Feb 27 19:13:09 EST 2006


Following Ron Adam solution (and using [] instead of list() in the last
line), this may be a possible solution of the problem, that is often
quite fast:

def psort16(s1, s2):
    try:
        d = dict(izip(s2, s1))
    except TypeError:
        _indices = range(len(s1))
        _indices.sort(key=s2.__getitem__)
        s1[:] = map(s1.__getitem__, _indices)
    else:
        if len(d) == len(s1):
            s1[:] = [d[v] for v in sorted(d)]
        else:
            _indices = range(len(s1))
            _indices.sort(key=s2.__getitem__)
            s1[:] = map(s1.__getitem__, _indices)

Bye,
bearophile




More information about the Python-list mailing list