Is there a simple and quick way to use sum() with non-integer values?
So I can use it like this:
class Foo(object):
def __init__(self,bar)
Try:
import operator
result=reduce(operator.add, mylist)
sum() works probably faster, but it is specialized for builtin numbers only. Of course you still have to provide a method to add your Foo() objects. So full example:
class Foo(object):
def __init__(self, i): self.i = i
def __add__(self, other):
if isinstance(other, int):
return Foo(self.i + other)
return Foo(self.i + other.i)
def __radd__(self, other):
return self.__add__(other)
import operator
mylist = [Foo(42), Foo(36), Foo(12), 177, Foo(11)]
print reduce(operator.add, mylist).i