Scala 变量在 for-each 循环/字符串被截断后重置



我正在做一个Spark项目。在下面的代码中,我有一个字符串,我用它来收集我的结果,以便稍后写入文件(我知道这不是正确的方法,我只是检查方法返回的Tuple3内部的内容)。字符串在每个循环之后被截断。这是我代码的相关部分:

val newLine = sys.props("line.separator") // also tried "n". I am using OS X.
var str = s"*** ${newLine}"
for (tuple3 <- ArrayOfTuple3s) {
  for (list <- tuple3._3) {
    for (strItem <- list) {
      str += s"${strItem}, "
    }
    str += s"${newLine}"
  }
  str += s"${newLine}"
  println(tempStr)
}
print("str=" + str)

第一个println方法调用打印字符串的正确值(串联结果),但当循环结束时,str的值***(与第一个循环之前分配给它的值相同)。

编辑:我用StringBuilder替换了str不可变的String对象,但结果没有变化:

val newLine: String = sys.props("line.separator")
var str1: StringBuilder = new StringBuilder(15000)
for (tuple3 <- ArrayOfTuple3s) {
  for (list <- tuple3._3) {
    for (str <- list) {
      str1.append(s"${str}, ")
    }
    str1.append(s"${newLine}")
  }
  str1.append(s"${newLine}")
  println(str1.toString())
}
print("resulting str1=" + str1.toString())

编辑 2:我映射了 RDD 以直接获取 Tuple3 的第三个字段。此字段本身是列表数组的 RDD。我相应地更改了代码,但我仍然得到相同的结果(结果字符串为空,尽管在 for 循环中不是)。

val rddOfArraysOfLists = getArrayOfTuple3s(mainRdd).map(_._3)
for (arrayOfLists <- rddOfArraysOfLists) {
  for (list <- arrayOfLists) {
    for (field <- list) {
      str1.append(s"${field}, ")
    }
    str1.append(" -- ")
  }
  str1.append(s"${newLine}")
  println(str1.toString())
}

编辑4:我认为问题根本不在于字符串。所有类型的变量似乎都有问题。

var count = 0
for (arrayOfLists <- myArray) {
  count = arrayOfLists.last(3).toInt
  println(s"count=$count")
}
println(s"count=$count")

该值在循环内不为零,但在循环外为 0。知道吗?

编辑5:我无法发布整个代码(由于机密性限制),但这是它的主要部分。如果很重要,我正在Intellij Idea中的本地计算机上运行Spark(用于调试)。

System.setProperty("spark.cores.max", "8")
System.setProperty("spark.executor.memory", "15g")    
val sc = new SparkContext("local", getClass.getName)            
val samReg = sc.objectFile[Sample](sampleLocation, 200).distinct
val samples = samReg.filter(f => f.uuid == "dce03545e8034242").sortBy(_.time).cache()
val top3Samples = samples.take(3)
for (sample <- top3Samples) {
  print("sample: ")
  println(s"uuid=${sample.uuid}, time=${sample.time}, model=${sample.model}")
}
val firstTimeStamp = samples.first.time
val targetTime = firstTimeStamp + 2592000 // + 1 month in seconds (samples during the first month)
val rddOfArrayOfSamples = getCountsRdd(samples.filter(_.time <= targetTime)).map(_._1).cache()
// Due to confidentiality matters, I cannot reveal the code, 
// but here is a description:
// I have an array of samples. Each sample has a few String fields 
// and is represented by a List[String]
// The above RDD is of the type RDD[Array[List[String]]]. 
// It contains only a single array of samples
// (because I passed a filtered set of samples to the function), 
// but it may contain more.
// The fourth field of each sample (list) is an increasing number (count)
println(s"number of arrays in the RDD: ${rddOfArrayOfSamples.count()}")
var maxCount = 0
for (arrayOfLists <- rddOfArrayOfSamples) {
  println(s"Last item of the array (a list)=${arrayOfLists.last}")
  maxCount = arrayOfLists.last(3).toInt
  println(s"maxCount=${maxCount}")
}
println(s"maxCount=${maxCount}")

输出:

示例:uuid=dce03545e8034242,时间=1360037324,模型=Nexus 4

示例:uuid=dce03545e8034242,时间=1360037424,模型=Nexus 4

示例:uuid=dce03545e8034242,时间=1360037544,模型=Nexus 4

RDD 中的阵列数量:1

数组的最后一项(列表)=List(dce03545e8034242, Nexus 4, 1362628767, 32, 2089, 0.97, 0.15999999999999992, 0)

最大计数=32

最大计数=0

在评论中将我的解释升级为答案:

请参阅对某个相关问题的回答:

不要涉及太多细节,但是当您运行不同时 RDD上的转换(map,flatMap,filter等),您的 转换代码(闭包)为:

在驱动程序节点上序列化,
传送到群集中的相应节点,
反序列化,
并最终在节点上执行

代码中的for只是map的语法糖。

因此,每个执行更新maxCount与调用程序中的maxCount不同。那个永远不会改变。

这里的教训是不要使用在块外更新变量的闭包(块)

由于您没有发布完整的示例,因此我不得不仲裁代码的某些部分。

对于我所做的第 4 次编辑:

val myArray = Array(
  List(List(0, 0, 0, 0), List(0, 0, 0, 0), List(0, 0, 0, 0)),
  List(List(1, 1, 1, 1), List(1, 1, 1, 1), List(1, 1, 1, 1)),
  List(List(2, 2, 2, 2), List(2, 2, 2, 2), List(2, 2, 2, 2))
)

在 REPL 中运行:

var count = 0
for (arrayOfLists <- myArray) {
  count = arrayOfLists.last(3).toInt
  println(s"count=$count")
}
println(s"count=$count")

我得到:

scala> for (arrayOfLists <- myArray) {
     |   count = arrayOfLists.last(3).toInt
     |   println(s"count=$count")
     | }
count=0
count=1
count=2
scala> println(s"count=$count")
count=2

该值在循环内不为零在循环外为非零。

如果您请发布一个完整的示例,也许我们可以为您提供更多帮助。

最新更新