2017-04-02 157 views
0

這可能是非常簡單的問題。我有一個名爲「List1」的列表,其中包含以下整數對列表。scala和遍歷列表中的所有第一元素和第二元素

的List1 =列表((1,2),(3,4),(9,8),(9,10))

輸出應爲:

R1 =(1,3,9,9)//列表((,2),(3 ,4),(9 ,8),(9 ,10))
R2 =(2,4,8,10)// List((1,),(3,),(9,),(9,))

array r1(Array[int]) should contains set of all first integers of each pair in the list. 
array r2(Array[int]) should contains set of all second integers of each pair 

回答

3

只需使用unzip

scala> List((1,2), (3,4), (9,8), (9,10)).unzip 
res0: (List[Int], List[Int]) = (List(1, 3, 9, 9),List(2, 4, 8, 10)) 
+0

感謝您提供這樣精確的解決方案 –

1

使用foldLeft

val (alist, blist) = list1.foldLeft((List.empty[Int], List.empty[Int])) { (r, c) => (r._1 ++ List(c._1), r._2 ++ List(c._2))} 

Scala的REPL

scala> val list1 = List((1, 2), (3, 4), (5, 6)) 
list1: List[(Int, Int)] = List((1,2), (3,4), (5,6)) 

scala> val (alist, blist) = list1.foldLeft((List.empty[Int], List.empty[Int])) { (r, c) => (r._1 ++ List(c._1), r._2 ++ List(c._2))} 
alist: List[Int] = List(1, 3, 5) 
blist: List[Int] = List(2, 4, 6) 
+0

感謝您的回答。 –

相關問題