"Newbie" questions - "unique" sorting ?

Fredrik Lundh fredrik at pythonware.com
Sat Jun 28 06:01:24 EDT 2003


Anton Vredegoor wrote:

> My personal observation is that *everything* I write in Python is a
> candidate for improvement in only a few months time because of my
> changing perspectives on the matter. For another perspective on the
> "lulu" code for example, try this :
>
>     trans = [string.lower(chr(i)) for i in range(256)]
>     for i in range(256):
>         if not trans[i] in string.letters: trans[i] = ' '
>     trans = ''.join(trans)
>
> I think this is both a line or so shorter than the original code and
> is probably also a bit clearer.

shorter, but not necessarily clearer (code that contains "".join is
never clear, in my experience, and the and/or trick doesn't make
things better):

trans = "".join([chr(x).isalpha() and chr(x).lower() or " " for x in range(256)])

but on the other hand, this gives you room for a two lines of
comments, explaining the intent of this piece of code.

you can trade performance for a source code character or two:

trans = "".join([(" ", chr(x).lower())[chr(x).isalpha()] for x in range(256)])

fwiw, I'd probably spell it all out, to make it all obvious:

# map letters to lowercase, and everything else to spaces
trans = range(256)
for i in trans:
    ch = chr(i)
    if ch.isalpha():
        trans[i] = ch.lower()
    else:
        trans[i] = " "
trans = string.join(trans, "")

but that's probably because I have a two-dimensional brain and a
working return key ;-)

</F>








More information about the Python-list mailing list