Python: method call in map function

map() and a list comprehension is roughly equivalent:

map(function, list1)
[function(i) for i in list1]

What if the function we want to use is a method?

[i.function() for i in list1]
map(.function, list1) # error!
map(run_method(function), list1) # error!

How could I perform such manipulations with map?

+3
source share
2 answers

Would you use operator.methodcaller():

from operator import methodcaller

map(methodcaller('function'), list1)

methodcaller()accepts additional arguments, which are then passed to the called method; methodcaller('foo', 'bar', spam='eggs')(object)is the equivalent object.foo('bar', spam='eggs').

list1 , , , , unbound map , , , :

map(str.lower, list_of_strings)

str.lower - str.

, map() . map() , C. map() zip() , map() Python 3 .

, () , Python, .

+9

, .

map(lambda x: type(x).function(), list1)

,

map(lambda x: x.function(), list1)

, , Python , - f**g(x) == f(g(x)).

map(type**function, list1)
0

All Articles