我有以下代码:
class Test:
def __init__(self,data):
self.x = data[0]
self.y = data[1]
我在翻译中尝试这个:
>>> a = Test([1,2])
>>> b = Test([1,2])
>>> c = Test([1,2])
>>> reduce(lambda x,y: x.x + y.x, [a,b,c])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'int' object has no attribute 'x'
虽然这有效:
>>> map(lambda x: x.x, [a,b,c])
[1, 1, 1]
编译器版本:Python 2.7
答案 0 :(得分:4)
你误解了reduce()
的工作原理;到目前为止,x
是结果。您的lambda
返回整数,因此x
在第一次调用后绑定到整数,而不是Test
实例。
reduce()
执行此操作:
a
和b
并将其传递给lambda。将返回值作为累计结果。 c
并将累计结果和c
传递给lambda。累积结果为整数,您的呼叫失败。如果您需要它是Test
对象,请始终返回一个:
reduce(lambda x, y: Test([x.x + y.x, 0]), [a, b, c])
现在,累计值的属性 。
。另一种方法是通过为累加器提供.x
初始值来一直使用整数:
reduce()
现在reduce(lambda x, y: x + y.x, [a, b, c], 0)
始终是一个整数,从x
开始。
答案 1 :(得分:2)
reduce
是累积的。所以它需要前面表达式的结果并添加到它。来自reduce
的帮助:
减少(...) reduce(function,sequence [,initial]) - &gt;值
Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
关键词是:reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5)
。
因此,在第一次计算之后,使用结果(整数),并且因为整数没有x
,所以你得到了例外。