Scala将字符串拆分为元组

pri*_*sia 9 string split scala tuples list

我想在有4个元素的空白上拆分一个字符串:

1 1 4.57 0.83
Run Code Online (Sandbox Code Playgroud)

我试图转换成List [(String,String,Point)],这样前两个分裂是列表中的前两个元素,最后两个是Point.我正在做以下但它似乎不起作用:

Source.fromFile(filename).getLines.map(string => { 
            val split = string.split(" ")
            (split(0), split(1), split(2))
        }).map{t => List(t._1, t._2, t._3)}.toIterator
Run Code Online (Sandbox Code Playgroud)

Ran*_*ulz 14

这个怎么样:

scala> case class Point(x: Double, y: Double)
defined class Point

scala> s43.split("\\s+") match { case Array(i, j, x, y) => (i.toInt, j.toInt, Point(x.toDouble, y.toDouble)) }
res00: (Int, Int, Point) = (1,1,Point(4.57,0.83))
Run Code Online (Sandbox Code Playgroud)


Den*_*kiy 10

您可以使用模式匹配从数组中提取所需内容:

    case class Point(pts: Seq[Double])
    val lines = List("1 1 4.34 2.34")

    val coords = lines.collect(_.split("\\s+") match {
      case Array(s1, s2, points @ _*) => (s1, s2, Point(points.map(_.toDouble)))
    })
Run Code Online (Sandbox Code Playgroud)

  • 这不能为我编译,我添加了另一个类似的答案,编译 - 我无法让代码在评论中正确显示.我很想知道如果其他人知道如何使用收集. (2认同)