【问题标题】:Scala : How to convert a List[String] to List[List[String]]Scala:如何将 List[String] 转换为 List[List[String]]
【发布时间】:2020-01-11 20:58:36
【问题描述】:

我有一个 scala 列表

scala> c
res18: List[String] = List(123  asd, 234 zxc)

我想要这样的东西

List(List(123,  asd),List(234, zxc))

我怎样才能做到这一点?我试过了

scala> var t = for (x <- c) x.split("\t")
t: Unit = ()

如何按空格分割列表中的每个元素,然后将结果分配为列表列表?

【问题讨论】:

    标签: regex list scala for-loop functional-programming


    【解决方案1】:

    另一种方法是使用map,如果你只有一个步骤,通常更易读:

    c.map(_.split(" ").toList)
    

    【讨论】:

      【解决方案2】:

      你需要使用yield关键字从for循环返回一个列表:

      var result = for (x <- c) yield x.split(" ")
      

      但这会导致List[Array[String]], if you want to have innerList`,使用:

      var result = for (x <- c) yield x.split(" ").toList
      

      【讨论】:

      • 或等价的脱糖c.map(_.split(" ").toList)
      • @Thilo 不是真的,这将导致单个List,您必须改用map
      • 我可以将其转换为 Seq 列表吗?基本上我想将其转换为数据框
      猜你喜欢
      • 1970-01-01
      • 2019-09-10
      • 2013-08-26
      • 2021-09-17
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      相关资源
      最近更新 更多