[Tutor] Multifunction mapping

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 30 Apr 2002 10:27:19 -0700 (PDT)


On Tue, 30 Apr 2002, Jordan, Jay 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)
> 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.

It's possible to do most of what you want with a single map:

###
>>> ''.join(map(lambda l: "%03d" % ord(l), letters))
'097098099100101102103104105'
###

We need a little extra to join the elements into a single string, because
mapping across a list will return a list of the results.


Python offers an alternative syntax for this using list comprehensions:

###
>>> ["%03d" % ord(l) for l in letters]
['097', '098', '099', '100', '101', '102', '103', '104', '105']
###


Good luck!