mapping a method to a list?

Tim Hochberg tim.hochberg at ieee.org
Wed Aug 8 16:45:03 EDT 2001


Oops. I apparently posted a blank message, sorry...brain not working today.

Anyway, this would work now:

   class Monty:
       def __init__(self, text):
           self.text = text

       def __str__(self):
           return "Monty(%s)" % self.text

       __repr__ = __str__

       def spammify(self):
           return Monty("spam & %s" % self.text)

   l = map(Monty, ["eggs", "baked beans", "sausage"])
   print l
   print map(Monty.spammify, l)

This obviously won't work for strings now, but it's possible that with the
great type-class unification that is upcoming that this may "just work".

<pause for download>

Well yes indeed. Using python 2.2a1 we can do:

>>> s = ["eggs", "baked beans", "sausage"]
>>> print map(str.upper, s)
['EGGS', 'BAKED BEANS', 'SAUSAGE']

Cool!

-tim


<gyromagnetic at excite.com> wrote in message
news:3b7193b8.137917594 at 127.0.0.1...
> Thank you all for the suggestions.
>
> I was aware of the list comprehesions solution. In fact, I almost put
> that in my note as one way I knew of to solve the problem. That type
> of solution would certainly suffice for the example I gave. I guess I
> was looking for some more general information about the capabilities
> of map.
>
> The solution using the lambda form that Just and Steve suggested was,
> I guess, what I was looking for. However, I thought there might be
> some special symbol prepended to the method that would indicate that
> the method was to be applied to each of the items in the list;  I
> chose the (apparently confusing) symbol '?'.
>
> -Brad





More information about the Python-list mailing list