[Tutor] Multifunction mapping

Remco Gerlich scarblac@pino.selwerd.nl
Tue, 30 Apr 2002 18:43:55 +0200


On  0, "Jordan, Jay" <jay.jordan@eds.com> wrote:
> how would it be possible to multi finction a map statement. Consider the
> following. 
> 
> I have a sequence of characters  (a,b,c,d,e,f,g,h,i)
> I want to convert the whole list to their ascii codes (ord)
> (61,62,63,64,65,66,67,68,69)
> I want to zfill them all to three digits
> (061,062,063,064,065,066,067,068,069)

zfill? I don't know what that is.

I'll assume you want to convert them into strings, filling them to three
characters with leading zeroes when necessary.

> and then concatenate the whole list into a single string
> (061062063064065066067068069)
> 
> Can that be done with a single map statement? Python is such an elegant
> language for doing big complicated things with just a very few statements so
> I am certan there has to be a better way than running through the list one
> at a time or mapping, writing, mapping, writing, mapping, writing.

Shorter is not better. Clearer is better. Something can be obfuscated both
by making it too short and by making it too verbose.

The shortest way to do this is

L = "abcdefghij"

s = ''.join(map(lambda x: '%03d' % ord(x), L))

or with a list comprehension, even shorter:

s = ''.join(['%03d' % ord(x) for x in L])

Personally I don't think this is the best way though - too much happens on
one line. I'd prefer

import string

L = "abcdefghij"
ords = [ord(x) for x in L]
strs = ['%03d' % o for o in ords]
s = string.join(strs, '')

Although maybe this is slightly too much on the verbose side, it is easier
to see which steps are taken.

Note the use of the % string formatting operator to get a number that's
filled up with leading zeroes, and string.join(list, '') or ''.join(list) to
join the parts together with nothing in between.

-- 
Remco Gerlich