【问题标题】:How to add every element of a list at the end of every element of another list in scala?如何在scala中另一个列表的每个元素的末尾添加列表的每个元素?
【发布时间】: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]

感谢您的帮助。

【问题讨论】:

  • 您也可以使用zipmap 来执行此操作(可能会更容易)
  • 另外,我建议您将 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


【解决方案1】:

尽量避免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))

我建议使用数组的unapply 来实现getValue,但你可以保留你的实现!

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

【讨论】:

  • @fleur,我的荣幸!如果它完全回答了您的问题,请毫不犹豫地接受答案
  • 已被接受。如果我想用 foldLeft 来做这件事,你知道吗?还是 foldRight?
  • 您可能想要使用 foldRight,以避免每次添加元素时都复制完整的列表。想法如下:Cars_tmp.zip(Values_tmp).foldRight(List[String]()) {case ((car, value), acc) => (car + value) :: acc}。但是,对于长度不等的列表,这将静默失败:)
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多