【问题标题】:scala filter a list based on the values of another listscala 根据另一个列表的值过滤列表
【发布时间】: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)

【问题讨论】:

    标签: list scala filter


    【解决方案1】:

    短一点:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        使用一个 for comprehension 去糖成 flatMapwithFilter(惰性过滤),像这样,

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-23
          • 1970-01-01
          相关资源
          最近更新 更多