python's sum() and non-integer values

前端 未结 6 1623
耶瑟儿~
耶瑟儿~ 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:34

    Or if you don't want to import anything,

    result = reduce((lambda x,y:x+y), mylist)
    

    Another small advantage is that you don't have to necessarily declare an __add__ method as part of your Foo objects, if this happens to be the only circumstance in which you'd want to do addition. (But it probably wouldn't hurt to define __add__ for future flexibility.)

提交回复
热议问题