【问题标题】:Not able to understand fold() behavior in spark [duplicate]无法理解 spark 中的 fold() 行为 [重复]
【发布时间】:2018-06-30 16:15:52
【问题描述】:

我是新来的火花。我已经执行了以下火花程序,

val spark = SparkSession.builder().appName("FoldFunction").master("local").getOrCreate()
    val data = spark.sparkContext.parallelize(List(("Maths", 10), ("English", 10), ("Social", 10), ("Science",10)))
    val extraMarks = ("extra", 10)
    val foldedData = data.fold(extraMarks){ (acc, marks) => val add = acc._2 + marks._2
      ("total", add)}

    println(foldedData)

根据我的分析,代码将在总分中加 10 分。但我得到的答案是(total,60)

谁能解释一下我的分析是否正确?

【问题讨论】:

    标签: apache-spark


    【解决方案1】:

    api文档说如下

    * @param zeroValue the initial value for the accumulated result of each partition for theopoperator, and also the initial value for the combine results from different partitions for theopoperator - this will typically be the neutral element (e.g.Nilfor list concatenation or0for summation) * @param op an operator used to both accumulate results within a partition and combine results from different partitions */ def fold(zeroValue: T)(op: (T, T) => T): T

    通常zeroValue 设置为0Nil

    但是您的zeroValue("extra", 10),它是在最后一次累积过程中再次添加的,这就是您获得(total,60) 的方式

    让我们一步一步来

    起初acc(extra,10) marks(Maths,10) 所以10+10=20(total, 20)
    第二个acc(total,20) marks(English,10) 所以20+10=30(total, 30)
    第三个acc(total,30) marks(Social,10) 所以30+10=40(total, 40)
    第四个acc(total,40) marks(Science,10) 所以40+10=50(total, 50)
    累积将zeroValue (extra,10)folded (total,50) 相加,所以 10+50=60(total, 60)

    【讨论】:

    • 您能详细解释一下吗?但我仍然觉得结果应该是 50。
    猜你喜欢
    • 2019-09-07
    • 1970-01-01
    • 2015-12-17
    • 2013-01-20
    • 1970-01-01
    • 2016-07-03
    • 2015-06-26
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多