[英]unsupported operand type error when adding objects within list using sum function
I have a Serie
class implemented to represent series of data and it's tag. 我有一个Serie
类,用于表示一系列数据及其标记。 When I add Serie
objects and also numbers I get the expected output. 当我添加Serie
对象和数字时,我得到了预期的输出。 However when I sum the same elements within a list I get following error message: 但是,当我对列表中的相同元素求和时,我得到以下错误消息:
TypeError: unsupported operand type(s) for +: 'int' and 'Serie' TypeError:+:'int'和'Serie'的不支持的操作数类型
As a toy example code to understand the problem we can use: 作为一个玩具示例代码来理解我们可以使用的问题:
import pandas as pd
import numpy as np
class Serie(object):
def __str__(self):
s = "> SERIE " + str(self.tag) + ": \n"
s += str(self.data)
return s
def __init__(self, tag=None, data=pd.DataFrame()):
"""
Creates object Serie
@type tag: str
@param tag: Tag for the Serie
"""
self.tag = tag
self.data = data
def __add__(self, other):
if isinstance(other, int) or isinstance(other, float):
tag = str(other) + "+" + self.tag
serie = Serie(tag)
serie.data = self.data + other
else:
try:
tag = self.tag + "+" + other.tag
except:
print ("ERROR: You can't add to somehing that is not a Serie or a number." )
return None
serie = Serie(tag)
serie.data = self.data + other.data
return serie
s1 = Serie("fibonacci",pd.Series([1,1,2,3,5,8]))
s2 = Serie("2power",pd.Series(np.linspace(1,6,6)**2))
s3 = 10
sumSerie = s1+s2+s3
print sumSerie
This prints the result as expected: 这将按预期打印结果:
>>>
> SERIE 10+fibonacci+2power:
0 12.0
1 15.0
2 21.0
3 29.0
4 40.0
5 54.0
dtype: float64
However when I run following lines: 但是当我运行以下行时:
l = [s1,s2,s3]
sum(l)
I get error message: 我收到错误消息:
sum(l) TypeError: unsupported operand type(s) for +: 'int' and 'Serie' sum(l)TypeError:+:'int'和'Serie'不支持的操作数类型
And same error message is displayed when I run: 运行时会显示相同的错误消息:
l2 = [s1,s2]
sum(l2)
But in l2
list there is no int
variable. 但是在l2
列表中没有int
变量。
Why is this error message being displayed? 为什么会显示此错误消息? This is confusing as I was able to sum the objects outside the list. 这是令人困惑的,因为我能够将列表外的对象相加。
Is there something I can do in order to achieve performing the sum of the objects within the list? 为了实现列表中对象的总和,我能做些什么吗?
As suggested in the comments, I added the __radd__
to correctly overload the add method. 正如评论中所建议的那样,我添加了__radd__
来正确地重载add方法。 So I added the below lines to the Serie
class: 所以我在Serie
类中添加了以下行:
def __radd__(self,other):
return self.__add__(other)
Then the sum works. 然后总和工作。 But not as expected. 但不如预期的那样。
If I run the below code: 如果我运行以下代码:
>>> print sum(l)
I get this output: 我得到这个输出:
> SERIE 10+0+fibonacci+2power:
0 12.0
1 15.0
2 21.0
3 29.0
4 40.0
5 54.0
dtype: float64
Which is definitely not the same I expected. 这绝对不是我预期的那样。 There is a +0
extra within the tag. 标签内有额外的+0
。 How can this be? 怎么会这样? However if I use the option I stated in my answer print np.array(l).sum()
the result is correct. 但是,如果我使用我在答案中描述的选项print np.array(l).sum()
,结果是正确的。
After overloading add method correctly I was suggested to use below method to perform the sum as expected: 重载后正确添加方法我建议使用以下方法按预期执行总和:
reduce(lambda a, b: a+b, l)
This approach worked to be able to use sum
function for the list and get the correct result. 这种方法的作用是能够对列表使用sum
函数并获得正确的结果。
As stated by pault in the comments in sum
method "start defaults to 0" as detailed in sum function's documentation . 正如指出pault在评论sum
法“开始默认为0”中详细说明和函数的文档 。 That was why the extra +0
was being added to the tag before. 这就是之前额外的+0
被添加到标签的原因。
In conclusion I believe I would preferrably use the option using numpy.sum
function instead: 总之,我相信我最好使用numpy.sum
函数来代替:
np.array(l).sum()
Not sure why using the sum function is not possible. 不确定为什么不能使用sum函数。 But a workaround to get the desired output from the lists would be to create a numpy
array from the list and use numpy.sum
function as you can see below: 但是从列表中获取所需输出的解决方法是从列表中创建一个numpy
数组并使用numpy.sum
函数,如下所示:
np.array(l).sum()
This gives the sum of the objects from the list as expected. 这将按预期给出列表中对象的总和。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.