【问题标题】:Python reduce explanationPython减少解释
【发布时间】:2012-11-16 04:52:29
【问题描述】:

我无法理解以下代码段:

>>> lot = ((1, 2), (3, 4), (5,))
>>> reduce(lambda t1, t2: t1 + t2, lot)
(1, 2, 3, 4, 5)

reduce 函数如何产生 (1,2,3,4,5) 的元组?

【问题讨论】:

  • 重点是元组上的+是串联(不是算术加法)!
  • 您了解reduce() 函数提供的一般抽象吗?我认为尝试理解 reduce 的每一个特定用法并不是很有见地
  • @phant0m 我明白 reduce() 函数提供了什么。但是我对这个特定示例中的+ 感到困惑,我认为这是一个算术加法。

标签: python functional-programming reduce


【解决方案1】:

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

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.

【讨论】:

    【解决方案2】:

    让我们追踪reduce

    结果 = (1,2) + (3,4)

    结果 = 结果 + (5, )

    请注意,您的归约会连接元组。

    【讨论】:

      【解决方案3】:

      如果你把lambda分解成一个函数会更容易,所以更清楚发生了什么:

      >>> def do_and_print(t1, t2):
          print 't1 is', t1
          print 't2 is', t2
          return t1+t2
      
      >>> reduce(do_and_print, ((1,2), (3,4), (5,)))
      t1 is (1, 2)
      t2 is (3, 4)
      t1 is (1, 2, 3, 4)
      t2 is (5,)
      (1, 2, 3, 4, 5)
      

      【讨论】:

        【解决方案4】:

        reduce 接受一个函数和一个迭代器作为参数。该函数必须接受两个参数。

        reduce 的作用是遍历可迭代对象。首先它将前两个值发送到函数。然后它将结果与下一个值一起发送,依此类推。

        因此,在您的情况下,它需要元组中的第一项和第二项,(1,2) 和 (3,4) 并将它们发送到 lambda 函数。该函数将它们加在一起。结果与第三项一起再次发送到 lambda 函数。由于元组中没有其他项目,因此返回结果。

        【讨论】:

          【解决方案5】:

          reduce() 按顺序应用一个函数,链接一个序列的元素:

          reduce(f, [a,b,c,d], s)
          

          相同
          f(f(f(f(s, a), b), c), d)
          

          等等。在你的情况下,f() 是一个 lambda 函数 (lambda t1, t2: t1 + t2),它只是将它的两个参数相加,所以你最终得到

          (((s + a) + b) + c) + d
          

          并且因为添加序列的括号没有任何区别,这是

          s + a + b + c + d
          

          或者你的实际值

          (1, 2) + (3, 4) + (5,)
          

          如果s 没有给出,第一项就没有完成,但通常中性元素用于s,所以在你的情况下() 是正确的:

          reduce(lambda t1, t2: t1 + t2, lot, ())
          

          但是没有它,只有lot 没有元素(TypeError: reduce() of empty sequence with no initial value)时才会遇到麻烦。

          【讨论】:

            猜你喜欢
            • 2018-01-23
            • 1970-01-01
            • 2020-01-20
            • 1970-01-01
            • 2014-01-08
            • 2016-02-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多