2014-10-20 113 views
1

我想从列表中唯一有效的值(表(表())),例如,如何从scala中的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

这是用':'语法吗?除非它是你的自定义操作符,否则它看起来不像有效的scala代码。 – 2014-10-20 11:39:42

+0

我第一次展示的是我现在得到的......它经过了一些计算。所以只会产生真实的情况值。从这个计算中得到了“自信:66.0”。整行“书橡皮擦 - >笔,自信:66.0”是一个字符串。但我只需要这个有效的字符串...不是列表(...( – rosy 2014-10-20 11:43:29

+1

噢好吧,现在就明白了,你应该明确地表明这种类型,这就是说,看看我的回答如下: – 2014-10-20 11:52:25

回答

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

您提供的例子并不十分清楚,但我看起来像一对夫妇的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

我不得不收集添加到@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) 

取而代之的收集,你也可以使用过滤器(_!=())

+2

万一有' Unit'在列表中,是的,这是一条可行的路线,但是不清楚'()'是否是一个String或Unit'' – 2014-10-20 13:13:58

+0

是的,你说得对,谢谢指出。 – mohit 2014-10-20 15:45:00

相关问题