简体   繁体   中英

traverse list in scala and group all the first elements and second elements

This might be pretty simple questions. I have a list named "List1" that contain list of integer pairs as below.

List1 = List((1,2), (3,4), (9,8), (9,10))

Output should be:

r1 = (1,3,9,9) //List(( 1 ,2), ( 3 ,4), ( 9 ,8), ( 9 ,10))
r2 = (2,4,8,10) //List((1, 2 ), (3, 4 ), (9, 8 ), (9, 10 ))

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  

Just use 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))

Use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM