Python 使用reduce时对象没有属性(但在地图上工作)

Python 使用reduce时对象没有属性(但在地图上工作),python,Python,我有以下代码: 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

我有以下代码:

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'

编译器版本:Python 2.7

您误解了
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
    总是一个整数,从
    0
    开始
    reduce
    是累积的。因此,它接受上一个表达式的结果并将其相加。从
    reduce
    上的帮助中:

    减少(…) 减少(函数,序列[,初始])->值

    关键短语是:
    reduce(lambda x,y:x+y,[1,2,3,4,5])计算(((1+2)+3)+4)+5)


    因此,在第一次计算之后,使用结果(一个整数),因为整数没有
    x
    ,所以得到例外。

    x.x+y.x
    这里,
    x
    int
    (它是1),并且它没有
    x
    属性(
    y
    是相同的)。@MarounMaroun
    x
    int
    ?x不是在那里测试的对象吗?@Sibi:不,不是,不是在第一次调用之后。
    reduce(lambda x, y: x + y.x, [a, b, c], 0)
    
    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.