简体   繁体   中英

scala filter a list based on the values of another list

I have two lists:

val l1 = List(1, 2, 3, 4)
val l2 = List(true, false, true, true)

Is there a nice and short way to filter l1 based on l2 ?

ris = List(1, 3, 4)

短一点:

list1.zip(list2).collect { case (x, true) => x }

One way could be zipping and then filtering 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理解,将其分解为flatMapwithFilter (延迟过滤),如下所示,

for ( (a,b) <- l1.zip(l2) if b ) yield a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM