使用python reduce()有点像javaScripts reduce(),但这样做失败
我想在Python中使用reduce(),但不知何故,我在某个时候失败了,我不知道为什么: 这是我的代码:使用python reduce()有点像javaScripts reduce(),但这样做失败,python,lambda,Python,Lambda,我想在Python中使用reduce(),但不知何故,我在某个时候失败了,我不知道为什么: 这是我的代码: def test(self): arry = [1,2,3,4,5] summe = reduce(lambda x, y: self.summa(x, y), arry) return summe def summa(self, x, y): if str(type(x)) == "<class 'int'>": arr =
def test(self):
arry = [1,2,3,4,5]
summe = reduce(lambda x, y: self.summa(x, y), arry)
return summe
def summa(self, x, y):
if str(type(x)) == "<class 'int'>":
arr = []
arr.append(x)
x = arr
return x.append(y)
append
返回None
,而不是列表。另外,使用isinstance(x,int)
而不是字符串比较。最后,summa
应该做什么?添加两个数字,还是建立一个新的列表?测试的预期结果是什么?好的,可能是我对reduce()的理解不正确。测试应该给我一个如下所示的数组:[1,3,6,10,15]。有没有可能用地图重写这个?我们的想法是拥有一个数组,然后得到另一个数组作为回报。我认为这更像是你定义的summa
的问题。另外,请注意,您正在尝试重新实现itertools.accumulate
<代码>列表(累加([1,2,3,4,5],λx,y:x+y))==[1,3,6,10,15]
。另外,请记住减少(f[x,y,z])
相当于f(f(x,y),z)
,而不是f(x,f(y,z))
。
return x.append(y)
AttributeError: 'NoneType' object has no attribute 'append'