sort one list using the values from another list
Ron Adam
rrr at ronadam.com
Tue Feb 28 14:12:49 EST 2006
bearophileHUGS at lycos.com wrote:
> 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
Looks good, but I think It would be simpler to just do.
def psort17(s1, s2):
try:
d = dict(izip(s2, s1))
assert len(d) != len(s2)
s1[:] = [d[v] for v in sorted(d)]
except Exception:
_indices = range(len(s1))
_indices.sort(key=s2.__getitem__)
s1[:] = map(s1.__getitem__, _indices)
We don't need to specify which exception. Any problems will just get
raised again on the second try it also fails.
Cheers,
Ron
More information about the Python-list
mailing list