【发布时间】:2021-01-21 09:21:09
【问题描述】:
我想在另一个列表的每个元素的末尾添加一个列表的元素。
我有:
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和map来执行此操作(可能会更容易) -
另外,我建议您将 TSV 数据解析为 案例类,以简化操作过程。
-
@user,谢谢您的回答。我尝试使用 map 和 zip,但它不起作用。你会怎么做呢?
-
Cars_tmp.zip(Values_tmp).map{case (car, value) => car + value} -
@user:谢谢。有用。您对使用 foldLeft 有想法吗?我不明白我的错误:发现:scala.collection.immutable.IndexedSeq[Any] required: List[String]
标签: arrays list scala fold foldleft