将 List[String] 按字符串拆分为单独的列表
Split a List[String] into separate list by a string
我很好奇如何根据另一个字符串将字符串列表拆分为单独的列表。
val animals: Map[Int, List[String]] = Map(5 -> List("cat", "dog", "mouse", "bear", "lion"),
(11 -> List("dog", "mouse", "tiger", "lion", "bear", "bird"),
(9 -> List("mouse", "dog", "mouse", "tiger", "bear"),
(15 -> List("cat", "tiger", "mouse")
)
我希望使用 "mouse"
获得与此类似的输出:
res0: Map[Int, List[String]] = Map(5 -> List(List("cat", "dog"), List("bear", "lion"))),
(11 -> List(List("dog"), List("tiger", "lion", "bear", "bird"))),
(9 -> List(List("dog"), List("tiger", "bear"))),
(15 -> List(List("cat", "tiger")))
)
这是我的确切情况,更具体地说,我只想知道一种简单的方法,我可以用字符串拆分一般 List[String]
。
看看这是否符合您的要求。
animals.map{case (k,lst) =>
k -> lst.foldRight(List(List.empty[String])){
case ("mouse", acc) => Nil::acc
case (anml, hd::tl) => (anml::hd)::tl
}.filter(_.nonEmpty)
}
我很好奇如何根据另一个字符串将字符串列表拆分为单独的列表。
val animals: Map[Int, List[String]] = Map(5 -> List("cat", "dog", "mouse", "bear", "lion"),
(11 -> List("dog", "mouse", "tiger", "lion", "bear", "bird"),
(9 -> List("mouse", "dog", "mouse", "tiger", "bear"),
(15 -> List("cat", "tiger", "mouse")
)
我希望使用 "mouse"
获得与此类似的输出:
res0: Map[Int, List[String]] = Map(5 -> List(List("cat", "dog"), List("bear", "lion"))),
(11 -> List(List("dog"), List("tiger", "lion", "bear", "bird"))),
(9 -> List(List("dog"), List("tiger", "bear"))),
(15 -> List(List("cat", "tiger")))
)
这是我的确切情况,更具体地说,我只想知道一种简单的方法,我可以用字符串拆分一般 List[String]
。
看看这是否符合您的要求。
animals.map{case (k,lst) =>
k -> lst.foldRight(List(List.empty[String])){
case ("mouse", acc) => Nil::acc
case (anml, hd::tl) => (anml::hd)::tl
}.filter(_.nonEmpty)
}