Working with a list in a more "pythonic" way

Jeff Epler jepler at unpythonic.net
Sun Apr 4 14:04:03 EDT 2004


[second try, python.org refused the message when the header contained
non-ascii characters.  As an aside, does anyone know how to configure
mutt to quote non-ascii characters in headers?]

First, you might want to map the letters to numbers all at once:
    phrase = [ord(x) - 65 for x in phrase]
then you could use an iterator to give the pairs:
    def pairs(seq):
        seq = iter(seq)
        a = seq.next()
        for j in seq:
            yield a, j
            a = j
Example usage:
    >>> list(pairs(range(5)))
    [(0, 1), (1, 2), (2, 3), (3, 4)]

So now you can write
    n = 0
    for first, second in pairs(phrase):
        n += soundScore[first][second]
taking care of IndexError as above.  You could also make soundScore a
dictionary, which I think was discussed elsewhere.
    n = 0
    for p in pairs(phrase):
        n += soundScore.get(p, 0)
or
    n = sum([soundScore.get(p, 0) for p in pairs(phrase)])

Jeff




More information about the Python-list mailing list