mapping a method to a list?
Steven D. Majewski
sdm7g at Virginia.EDU
Wed Aug 8 13:31:17 EDT 2001
On Wed, 8 Aug 2001, Tim Hochberg wrote:
>
> <gyromagnetic at excite.com> wrote in message
> news:3b716759.126576344 at 127.0.0.1...
>
> > Is there a way to map the .upper method to these items? Something
> > like, for example,
> > >>>>map(?.upper, val).
>
> Did you try the obvious thing? It should work. For example:
>
> class Monty:
> def spammify(self, text):
> return "spam & %s" % text
>
> l = ["eggs", "baked beans", "sausage"]
> m = Monty()
>
> print map(m.spammify, l)
[...]
>
> Or did you mean something completely different?
I think he meant (from the example) to map a method onto a list of
instances.
If they are all instances of the same class, then you can map the
unbound class method to the list of instances:
>>> class X:
... def __init__( self, val ):
... self.val = val
... def value(self):
... return self.val
...
>>> things = map( X, range(5) )
>>> map( X.value, things )
[0, 1, 2, 3, 4]
However, if there are any subclasses in the list, you may not get
the answer you're expecting:
>>> class Y(X):
... def value(self):
... return self.__class__.__name__ + ':' + str(self.val)
...
>>> Y(999).value()
'Y:999'
>>> things.append( Y( 999 ) )
>>> map( X.value, things )
[0, 1, 2, 3, 4, 999]
And it won't work at all if any of the classes are not subclasses of
the class method's class:
>>> map( Y.value, things )
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method value() must be called with instance as first
argument
So the best method is either to wrap the method in a lambda function:
>>> map( lambda x: x.value(), things )
[0, 1, 2, 3, 4, 'Y:999']
Or, in 2.*, us a list comprehension:
>>> [ x.value() for x in things ]
[0, 1, 2, 3, 4, 'Y:999']
-- Steve M.
More information about the Python-list
mailing list