如何在Scala中将列表的每个元素添加到另一个列表的每个元素的末尾?

问题描述

我想在另一个列表的每个元素的末尾添加一个列表的元素。

我有

val Cars_tmp :List[String] = List("Cars|10|Paris|5|Type|New|","Cars|15|Paris|3|Type|New|")
=> Result : List[String] = List("Cars|10|Paris|5|Type|New|","Cars|15|Paris|3|Type|New|")

val Values_tmp: List[String] = a.map(r =>  ((r.split("[|]")(1).toInt)/ (r.split("[|]")(3).toInt)).toString ).toList
=> Result : List[String] = List(2,5)

我想得到以下结果(Values_tmp的第一个元素与Cars_tmp的第一个元素连接,Values_tmp的第二个元素与Cars_tmp的第二个元素连接...),如下所示:

 List("Cars|10|Paris|5|Type|New|2","Cars|15|Paris|3|Type|New|5")

我试图这样做:

Values_tmp.foldLeft( Seq[String](),Cars_tmp) { case ((acc,rest),elmt) => ((rest :+ elmt)::acc) }

我遇到以下错误

console>:28: error: type mismatch;
found   : scala.collection.immutable.IndexedSeq[Any]
required: List[String]

谢谢您的帮助。

解决方法

尝试避免使用zip,当可迭代项的大小不相同时,它会默默地“失败”。 (在您的代码中,似乎两个列表的大小相同,但是对于更复杂的代码,这并不明显。)

您可以计算所需的“值”并将其即时连接:


val Cars_tmp: List[String] = List("Cars|10|Paris|5|Type|New|","Cars|15|Paris|3|Type|New|")

def getValue(str: String): String = {
    val Array(_,a,_,b,_) = str.split('|')  // Note the single quote for the split. 
    (a.toInt / b.toInt).toString
}

Cars_tmp.map(str => str + getValue(str))

我提出了使用getValue数组的unapply的实现,但是您可以保留实现!

def getValue(r: String) = ((r.split("[|]")(1).toInt)/ (r.split("[|]")(3).toInt)).toString