2013-02-20 192 views
7

我想在有4个元素空格分割字符串:斯卡拉分割字符串元组

1 1 4.57 0.83 

,我想转换成列表[(字符串,字符串,点),使得前两个拆分是列表中的前两个元素,最后两个是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 
+1

如果你想要一个元组为什么你说要转换为List? – 2013-02-20 03:47:11

+0

我同意,这应该更接近将字符串转换为List()元素 – 2013-12-04 00:40:58

回答

8

你可以使用模式匹配来提取您从阵列中需要的东西:

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

这不适合我编译,我添加了另一个类似的编译答案 - 我无法让代码在评论中正确显示。如果别人知道如何收集信息,我会很好奇。 – 2013-07-12 00:57:26

+0

来自'collect' *“API的API通过将部分函数应用于此列表中定义该函数的所有元素来构建一个新集合。”*。它就像'map'一样,但只保留部分函数 – 2013-07-12 09:47:00

1

您还没有转换的第三和第四代币成Point,也不是你的线条转换为List。此外,您不是将每个元素都渲染为Tuple3,而是将其渲染为List

以下应该更符合您的要求。

case class Point(x: Double, y: Double) // Simple point class 
Source.fromFile(filename).getLines.map(line => { 
    val tokens = line.split("""\s+""") // Use a regex to avoid empty tokens 
    (tokens(0), tokens(1), Point(tokens(2).toDouble, tokens(3).toDouble)) 
}).toList // Convert from an Iterator to List 
+0

PS:我没有测试这个。 – cheeken 2013-02-20 03:52:16

+0

我的Point类需要(IndexedSeq [Double]),所以如何从元组获得Indexed Seq? – 2013-02-20 04:01:33

13

如何:

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)) 
+0

的域中的元素,并且简单明了。您可能需要添加一个案例来处理输入错误。 – 2013-02-20 14:07:43

-1

有办法转换一个元组列表或SEQ ,单程是

scala> (1,2,3).productIterator.toList 
res12: List[Any] = List(1, 2, 3) 

Bu T作为你可以看到,返回类型为任何,而不是一个INTEGER

用于转换成不同的类型,您在模式中使用的 https://github.com/milessabin/shapeless

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

val splitLines = lines.split("\\s+") match { 
    case Array(s1, s2, points @ _*) => (s1, s2, Point(points.map(_.toDouble))) 
} 

而对于好奇Hlist中,@匹配将变量绑定到模式,因此points @ _*将变量点绑定到模式* _和* _匹配数组的其余部分,所以点最终成为Seq [String]。

+0

嗯..我得到scala.MatchError:[Ljava.lang.String; @ 7bfacd5d(类[Ljava.lang.String;) 我做错了什么? – Sergey 2015-08-14 11:14:22