How do you turn a Scala list into pairs?

2020-02-11 17:57发布

问题:

I am trying to split Scala list like List(1,2,3,4) into pairs (1,2) (2,3) (3,4), what's a simple way to do this?

回答1:

val xs = List(1,2,3,4)
xs zip xs.tail
  // res1: List[(Int, Int)] = List((1,2), (2,3), (3,4))

As the docs say, zip

Returns a list formed from this list and another iterable collection by combining corresponding elements in pairs. If one of the two collections is longer than the other, its remaining elements are ignored.

So List('a,'b,'c,'d) zipped with List('x,'y,'z) is List(('a,'x), ('b,'y), ('c,'z)) with the final 'd of the first one ignored.

From your example, the tail of List(1,2,3,4) is List(2,3,4) so you can see how these zip together in pairs.



回答2:

To produce a list of pairs (i.e. tuples) try this

List(1,2,3,4,5).sliding(2).collect{case List(a,b) => (a,b)}.toList


回答3:

List(1,2,3,4).sliding(2).map(x => (x.head, x.tail.head)).toList
res0: List[(Int, Int)] = List((1,2), (2,3), (3,4))


标签: scala