【发布时间】:2016-01-03 21:58:36
【问题描述】:
我有两个列表:
val l1 = List(1, 2, 3, 4)
val l2 = List(true, false, true, true)
有没有一种基于l2 过滤l1 的简单快捷的方法?
ris = List(1, 3, 4)
【问题讨论】:
我有两个列表:
val l1 = List(1, 2, 3, 4)
val l2 = List(true, false, true, true)
有没有一种基于l2 过滤l1 的简单快捷的方法?
ris = List(1, 3, 4)
【问题讨论】:
短一点:
list1.zip(list2).collect { case (x, true) => x }
【讨论】:
一种方法是压缩然后过滤l1.zip(l2).filter(_._2).map(_._1):
scala> l1.zip(l2)
res0: List[(Int, Boolean)] = List((1,true), (2,false), (3,true), (4,true))
scala> .filter(_._2)
res1: List[(Int, Boolean)] = List((1,true), (3,true), (4,true))
scala> .map(_._1)
res2: List[Int] = List(1, 3, 4)
【讨论】:
使用一个 for comprehension 去糖成 flatMap 和 withFilter(惰性过滤),像这样,
for ( (a,b) <- l1.zip(l2) if b ) yield a
【讨论】: