简体   繁体   中英

Scala extract from Seq of tuples

Here's a seq of tuples in Scala

val t = Seq((1,2,3),(4,5,6))

I like to extract the first element of each tuple into its own sequence, ie,

Seq(1,4)

How do I do this in Scala?

Simply use map and transform each tuple to its first element:

t.map(x => x._1)

Or shorter:

t.map(_._1)

The general form to extract more than one columns:

def extractColumns3[T1, T2, T3](t: Seq[(T1, T2, T3)]): (Seq[T1],   Seq[T2], Seq[T3]) =
t.foldLeft((Seq.empty[T1], Seq.empty[T2], Seq.empty[T3])) { (columns, row) ⇒
  (columns._1 :+ row._1, columns._2 :+ row._2, columns._3 :+ row._3)
}

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