【问题标题】:Split a List[String] into separate list by a string通过字符串将 List[String] 拆分为单独的列表
【发布时间】:2021-06-08 00:45:10
【问题描述】:

我很好奇如何根据另一个字符串将字符串列表拆分为单独的列表。

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]

【问题讨论】:

  • 您可以使用foldsplitAt 来执行此操作。更多信息可以在documentation中找到

标签: scala functional-programming higher-order-functions


【解决方案1】:

看看这是否符合你的要求。

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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2012-10-17
    • 2019-01-14
    相关资源
    最近更新 更多