2014-03-19 39 views
3

合併陣列我有3合併陣列在斯卡拉

Array("1", "2", "3") 

Array("orange", "Apple", "Grape") 

Array("Milk", "juice", "cream") 

我需要輸出

Array(Array("1", "orange", "Milk"), Array("2", "Apple", "juice"), Array("1", "Grape", "cream")) 

這可能與Scala的內置函數?

回答

4

只要你的陣列具有相同的長度,這可以使用zipmap

分兩步定義數組

scala> Array("1", "2", "3") 
res0: Array[String] = Array(1, 2, 3) 

scala> Array("orange", "Apple", "Grape") 
res1: Array[String] = Array(orange, Apple, Grape) 

scala> Array("Milk", "juice", "cream") 
res2: Array[String] = Array(Milk, juice, cream) 

zip在一起完成。 zip在壓縮結果創建的元組

scala> res0 zip res1 
res3: Array[(String, String)] = Array((1,orange), (2,Apple), (3,Grape)) 

scala> res3 zip res2 
res4: Array[((String, String), String)] = Array(((1,orange),Milk), ((2,Apple),juice), ((3,Grape),cream)) 

map的陣列變換嵌套元組陣列

scala> res4 map {case ((a,b),c) => Array(a,b,c) } 
res5: Array[Array[String]] = Array(Array(1, orange, Milk), Array(2, Apple, juice), Array(3, Grape, cream)) 
1

同樣對於

val a = Array("1", "2", "3") 
val b = Array("orange", "Apple", "Grape") 
val c = Array("Milk", "juice", "cream") 

然後

(a,b,c).zipped.map{ case(x,y,z) => Array(x,y,z) } 

提供

Array(Array(1, orange, Milk), Array(2, Apple, juice), Array(3, Grape, cream)) 

更新

然而,一個不同的方法來那些使用拉鍊,更簡單的

Array(a,b,c).transpose 

這允許任何數量的輸入陣列,而相比之下,拉鍊approachers這需要用於模式匹配的輸入數組的數量的先驗知識。