我期望reduce(add,lst)并且sum(lst)应该给我相同的结果,但是
In [18]: class p():
def __init__(self, x, y):
self.x=x ; self.y=y
def __repr__(self):
return "(%r,%r)"%(self.x,self.y)
def __add__(self, P):
return p(self.x+P.x, self.y+P.y)
....:
In [19]: pts=[p(1,0), p(2,1), p(-3,4)]
In [20]: from operator import add
In [21]: print reduce(add,pts)
(0,5)
In [22]: print sum(pts)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-98a81789d257> in <module>()
----> 1 print sum(pts)
TypeError: unsupported operand type(s) for +: 'int' and 'instance'
In [23]:
Run Code Online (Sandbox Code Playgroud)
当然我不理解某些东西,可能是显而易见的; 有人可以开导我吗?
Mar*_*ers 10
reduce()以pts[0]初始值开头(除非你给它一个明确的起始值),但sum()默认为0.从sum()功能文档:
sum(iterable[, start])
Sums 从左到右开始和可迭代的项目并返回总数.开始默认为0.
给sum()一个更好的开始值; 使用第一个对象就像reduce():
sum(pts[1:], pts[0])
Run Code Online (Sandbox Code Playgroud)
或合适的空值:
sum(pts, p(0, 0))
Run Code Online (Sandbox Code Playgroud)