sorting strings by size

Alex Martelli aleax at aleax.it
Thu Aug 9 09:21:51 EDT 2001


"Mark Robinson" <m.1.robinson at herts.ac.uk> wrote in message
news:3B7266C9.90706 at herts.ac.uk...
> Can anyone thing of a more eligant way of doing this? I am trying to
> extract the keys of my dict and sort them according to size, but this
> currently seems kinda crude
>
> temp = [(len(x), x) for x in motifs.keys()]
> temp.sort()
> temp.reverse()
> motiflist = [x[1] for x in temp]

You can probably save a tiny bit of effort here:

temp = [(-len(x), x) for x in motif.keys()]
temp.sort()
motiflist = [x[1] for x in temp]

i.e., no .reverse needed, just prepare your decorated
temporary-list appropriately.  Of course, this will
give a different order within each group of keys of
the same length, but you didn't mention that as a spec.

If you often find yourself having to sort a list based
on some function of its item, possibly with a reverse,
a different refactoring suggests itself:

def mrsort(thelist, thefun, reverse=0):
    temp = zip(map(thefun,thelist),thelist)
    # or temp = [(thefun(x),x) for x in thelist]
    temp.sort()
    if reverse: temp.reverse()
    return [x[1] for x in temp]

and once that is safely put away, just

motiflist = mrsort(motif.keys(), len, reverse=1)


Alex






More information about the Python-list mailing list