How to split a sequence into two pieces by predicate?

后端 未结 6 950
孤城傲影
孤城傲影 2020-12-02 11:35

How do I split a sequence into two lists by a predicate?

Alternative: I can use filter and filterNot, or write my own method, but isn\'t th

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 12:16

    If you want to split a list into more than 2 pieces, and ignore the bounds, you could use something like this (modify if you need to search for ints)

    def split(list_in: List[String], search: String): List[List[String]] = {
      def split_helper(accum: List[List[String]], list_in2: List[String], search: String): List[List[String]] = {
        val (h1, h2) = list_in2.span({x: String => x!= search})
        val new_accum = accum :+ h1
        if (h2.contains(search)) {
          return split_helper(new_accum, h2.drop(1), search) 
        }
        else {
        return accum
        }
      }
      return split_helper(List(), list_in, search)
    }
    
    // TEST
    
    // split(List("a", "b", "c", "d", "c", "a"), {x: String => x != "x"})
    

提交回复
热议问题