2014-11-08 108 views
1

我有如下列表 -如何使用scala從列表中創建單獨的列表?

List((name1,A1,176980), (name2,A2,0), (name3,A3,1948), (name4,A4,95676)) 

從以上列表,我想創建列表元素喜歡 - 分別部件1,element2的和元素3的單獨的列表。

我想單獨列出喜歡 -

List(name1,name2,name3,name4) 

List(A1,A2,A3,A4) 

List(176980,0,1948,95676) 

如何獲得上述列表使用Scala的???

回答

3

天真的解決方案:

val list = List(
    ("name1","A1",176980), 
    ("name2","A20",0), 
    ("name3","A3",1948), 
    ("name4","A4",95676)) 

list.map(_._1)  
list.map(_._2)  
list.map(_._3)  

一些期廣義版本:

def key(products: List[Product], num: Int) = { 
    products.map(_.productElement(num)) 
} 

key(list, 0) // res3: List[Any] = List(name1, name2, name3, name4) 
key(list, 1) // res4: List[Any] = List(A1, A20, A3, A4) 
key(list, 2) // res5: List[Any] = List(176980, 0, 1948, 95676) 

甚至與任何產品元數:

def key(products: List[Product], num: Int) = { 
    products.map { p => 
    Option(p) 
     .filter(_.productArity > num) 
     .map(_.productElement(num)) 
     .getOrElse(None) 
    } 
} 
1
scala> List(("name1","A1",176980), ("name2","A2",0), ("name3","A3",1948)) 
res9: List[(String, String, Int)] = List((name1,A1,176980), (name2,A2,0), (name3,A3,1948)) 

scala> res9.map(_._1) 
res10: List[String] = List(name1, name2, name3) 

scala> res9.map(_._2) 
res11: List[String] = List(A1, A2, A3) 

scala> res9.map(_._3) 
res12: List[Int] = List(176980, 0, 1948) 
6

如果你總是有3-元組,這裏有一個標準的方法:

scala> list.unzip3 
res1: (List[String], List[String], List[Int]) = 
(List(name1, name2, name3, name4),List(A1, A20, A3, A4),List(176980, 0, 1948, 95676)) 

還有unzip 2元組。