我有以下列表 -
List((name1,A1,176980), (name2,A2,0), (name3,A3,1948), (name4,A4,95676))
从上面的列表中我想分别创建像element1,element2和element3这样的列表元素的单独列表。
我想要单独的列表,例如 -
List(name1,name2,name3,name4)
List(A1,A2,A3,A4)
List(176980,0,1948,95676)
如何使用scala ???
获取上述列表答案 0 :(得分: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))
对于2元组,还有unzip
。
答案 1 :(得分: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)
}
}
答案 2 :(得分: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)