python's sum() and non-integer values

前端 未结 6 1625
耶瑟儿~
耶瑟儿~ 2020-12-01 18:04

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)
               


        
6条回答
  •  孤城傲影
    2020-12-01 18:36

    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
    

提交回复
热议问题