2013-02-20 187 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