1

I would like to know if there's a function similar to map but working for methods of an instance. To make it clear, I know that map works as:

map( function_name , elements )
# is the same thing as:
[ function_name( element ) for element in elements ]

and now I'm looking for some kind of map2 that does:

map2( elements , method_name )
# doing the same as:
[ element.method_name() for element in elements ]

which I tried to create by myself doing:

def map2( elements , method_name ):
    return [ element.method_name() for element in elements ]

but it doesn't work, python says:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'method_name' is not defined

even though I'm sure the classes of the elements I'm working with have this method defined.

Does anyone knows how could I proceed?

4

2 回答 2

4

operator.methodcaller() will give you a function that you can use for this.

map(operator.methodcaller('method_name'), sequence)
于 2013-06-28T16:17:26.603 回答
1

You can use lambda expression. For example

a = ["Abc", "ddEEf", "gHI"]
print map(lambda x:x.lower(), a)

You will find that all elements of a have been turned into lower case.

于 2015-08-31T19:22:08.337 回答