简体   繁体   English

Scala根据另一个列表的值过滤列表

[英]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 ? 有没有一种很好的,简短的方法来基于l2过滤l1

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) : 一种方法是压缩然后过滤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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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