我正在使用Scala从事Spark项目。我需要打印一个名为“ c”的列表的每个元素以及一个变量。我现在正在使用jdoodle运行此小代码,收到“ value foreach不是Any的成员”错误,并且错误消息指向print语句中的foreach。
object Graph {
def main(args: Array[String]) {
val line="1,2,3,4,5,6"
val a = line.split(",")
val b=Seq(a(0),a(0),a.drop(1).toList)
val c=b(2)
print(Seq((b(0),b(1)),(c.foreach{x=>print(s"($x,$b(1))")})))
}
}
我希望结果为类似[(1,1)(2,1)(3,1)(4,1)(5,1)(6,1)]
答案 0 :(得分:2)
val data = "1,2,3,4,5,6".split(",")
//safe even if data is an empty Array()
val res = data.foldRight(Seq.empty[(String,String)]){ case (n,arr) =>
(n,data.head) +: arr}
res.foreach(print) //(1,1)(2,1)(3,1)(4,1)(5,1)(6,1)
(与this mangled question类似。)
答案 1 :(得分:0)
val line =“ 1,2,3,4,5,6”
val lineOut = line.split(“,”)。toList.map(f =>(f,line.head))