简体   繁体   English

python 的 sum() 和非整数值

[英]python's sum() and non-integer values

Is there a simple and quick way to use sum() with non-integer values?有没有一种简单快捷的方法来使用具有非整数值的 sum() ?

So I can use it like this:所以我可以这样使用它:

class Foo(object):
    def __init__(self,bar)
        self.bar=bar

mylist=[Foo(3),Foo(34),Foo(63),200]
result=sum(mylist) # result should be 300

I tried overriding __add__ and __int__ etc, but I don't have found a solution yet我尝试覆盖__add____int__等,但我还没有找到解决方案

EDIT:编辑:

The solution is to implement:解决方案是实现:

 def __radd__(self, other):
    return other + self.bar

as Will suggested in his post.正如威尔在他的帖子中所建议的那样。 But as always, all roads lead to Rome, but I think this is the best solution since I don't need __add__ in my class但一如既往,条条大路通罗马,但我认为这是最好的解决方案,因为我的班级不需要__add__

Its a bit tricky - the sum() function takes the start and adds it to the next and so on它有点棘手 - sum() 函数开始并将其添加到下一个等等

You need to implement the __radd__ method:您需要实现__radd__方法:

class T:
    def __init__(self,x):
        self.x = x
    def __radd__(self, other):
        return other + self.x

test = (T(1),T(2),T(3),200)
print sum(test)

You may also need to implement the __radd__ function, which represents "reverse add" and is called when the arguments can't be resolved in the "forward" direction.您可能还需要实现__radd__函数,该函数表示“反向添加”并在无法在“正向”方向解析参数时调用。 For example, x + y is evaluated as x.__add__(y) if possible, but if that doesn't exist then Python tries y.__radd__(x) .例如,如果可能, x + y被评估为x.__add__(y) ,但如果它不存在,那么 Python 会尝试y.__radd__(x)

Since the sum() function starts with the integer 0 , the first thing it does is try to evaluate:由于sum()函数以整数0开头,因此它所做的第一件事就是尝试计算:

0 + Foo(3)

which will require that you implement Foo.__radd__ .这将要求您实现Foo.__radd__

Try:尝试:

import operator
result=reduce(operator.add, mylist)

sum() works probably faster, but it is specialized for builtin numbers only. sum() 的工作速度可能更快,但它仅适用于内置数字。 Of course you still have to provide a method to add your Foo() objects.当然,您仍然必须提供一种方法来添加 Foo() 对象。 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

Try using the __int__ method and then mapping each element in your list to the int function to get the values out:尝试使用__int__方法,然后将列表中的每个元素映射到int函数以获取值:

class Foo(object):
    def __init__(self,bar):
        self.bar = bar
    def __int__(self):
        return self.bar

mylist = [Foo(3),Foo(34),Foo(63),200]
result = sum(map(int,mylist))
print(result)

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.另一个小优势是您不必将__add__方法声明为 Foo 对象的一部分,如果这恰好是您想要添加的唯一情况。 (But it probably wouldn't hurt to define __add__ for future flexibility.) (但为未来的灵活性定义__add__可能不会有什么坏处。)

sum() (without integer hack) solution seems the cleanest; sum() (没有整数黑客)解决方案似乎是最干净的; because sum() starts with the zero, handle this case (from http://www.marinamele.com/2014/04/modifying-add-method-of-python-class.html ):因为sum()以零开头,请处理这种情况(来自http://www.marinamele.com/2014/04/modifying-add-method-of-python-class.html ):

def __radd__(self, other):
    if other == 0:
        return self
    else:
        return other.__add__(self)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM