rafa
rafa

Reputation: 795

execute an specific method of the instances in a list in python

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?

Upvotes: 1

Views: 716

Answers (2)

zyl1024
zyl1024

Reputation: 700

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.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798744

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

map(operator.methodcaller('method_name'), sequence)

Upvotes: 4

Related Questions