Reputation: 2405
Let's say we have a class which has an instance method that accepts another instance of that class, and then returns a new instance of that class.
An example of an this type of class is an integer. It has the __mul__
method, which accepts another integer and returns an integer, which is the product of both numbers.
Here's the problem. I have a class that implements a method like __mul__
. I have a list of instances of this class, and I want to apply the aforementioned method of the last object to the object before it, then take the result of that and apply it to the one before it, etc., until we have processed the entire list, and have ourselves one object.
A concrete example looks like this. Imagine we have a list of objects...
my_objs = [do, re, me, fa, so, la, te, do]
... And imagine they have the "combine" method, which follows the pattern outlined above, and we want to apply the procedure I outlined to it. You might think of it like this ...
my_objs_together = do.combine(re.combine(me.combine(fa.combine(so.combine(la.combine(te.combine(do)))))))
That's pretty gnarly, obviously. This makes me want to write a generic function like this...
def together(list_of_objects, method_name):
combined = list_of_objects[0]
for obj in list_of_objects[1:]:
combined = getattr(combined, method_name)(obj)
return combined
...But it occurs to me that there's likely already a standard library function that does this, right?
Upvotes: 1
Views: 88
Reputation: 2405
It's reduce! (I was in the middle of writing the question when I found it :/)
https://docs.python.org/2/library/functions.html#reduce
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
calculates((((1+2)+3)+4)+5)
.
Upvotes: 4