Thursday 26 April 2012

How do I apply a method to a sequence of objects? | Python

Use a list comprehension:
result = [obj.method() for obj in List]
More generically, you can try the following function:
def method_map(objects, method, arguments):
"""method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]""" nobjects = len(objects)
methods = map(getattr, objects, [method]*nobjects)
return map(apply, methods, [arguments]*nobjects)