我只想要List(List(List())中的有效值,例如
List(List(List(())), List(List(())), List(List(())), List(List(())), List(List(())), List(List(book eraser -> pen , confidence :66.0)))
List(List(List(())), List(List(Ink -> pen eraser , confidence :100.0)), List(List(())), List(List(pen Ink -> eraser , confidence :100.0)), List(List(())), List(List(Ink eraser -> pen , confidence :100.0)))
我只需要内部字符串,
book eraser -> pen , confidence :66.0
Ink -> pen eraser , confidence :100.0
pen Ink -> eraser , confidence :100.0
Ink eraser -> pen , confidence :100.0
答案 0 :(得分:2)
您提供的示例并不完全清楚,但我看起来有几个flatten
可能会有所帮助:
val a = List(List(List()), List(List("book eraser -> pen , confidence :66.0")), List(List()))
a.flatten.flatten // List[String] = List(book eraser -> pen , confidence :66.0)
答案 1 :(得分:2)
如果您编写这样的递归方法,则无论嵌套如何都可以拉出字符串。 (flatten
仅在所有内容嵌套到相同深度时才有效。)
def allStrings[A](xs: List[A]): List[String] = {
val ss = List.newBuilder[String]
def decompose(xs: List[_]) { xs match {
case (s: String) :: more => ss += s; decompose(more)
case (l: List[_]) :: more => decompose(l); decompose(more)
case x :: more => decompose(more)
case Nil =>
}}
decompose(xs)
ss.result
}
尽管如此,这是一种存储数据的奇怪方式。
(注意:所有decompose(more)
调用都是尾递归的,所以你不会遇到堆栈溢出问题。decompose(l)
是正常的递归,所以如果你的列表嵌套超过一千或者深层次,你可能想以不同的方式(例如基于堆的广度优先搜索)。)
答案 2 :(得分:1)
我必须将收集添加到@Gabriele,以获得所需的结果。
scala> List(List(List(())), List(List("Ink -> pen eraser , confidence :100.0")), List(List(())),List(List("pen Ink -> eraser , confidence :100.0")), List(List(())), List(List("Ink eraser -> pen , confidence :100.0")))
res0: List[List[List[Any]]] = List(List(List(())), List(List(Ink -> pen eraser ,confidence :100.0)),List(List(())), List(List(pen Ink -> eraser , confidence :100.0)), List(List(())),List(List(Ink eraser -> pen , confidence :100.0)))
scala> res0.flatten.flatten.collect{case str: String => str}
res1: List[String] = List(Ink -> pen eraser , confidence :100.0, pen Ink -> eraser , confidence :100.0, Ink eraser -> pen , confidence :100.0)
scala> val a = List(List(List(())), List(List("Ink -> pen eraser , confidence :100.0")), List(List(())), List(List("pen Ink -> eraser , confidence :100.0")), List(List(())), List(List("Ink eraser -> pen , confidence :100.0")))
scala> res0.flatten.flatten.collect{case str: String => str}
res4: List[String] = List(Ink -> pen eraser , confidence :100.0, pen Ink -> eraser , confidence :100.0, Ink eraser -> pen , confidence :100.0)
您也可以使用过滤器(_!=())
而不是收集