Scala sublist with index

114 Views Asked by At
input_list =        [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

Output 

 l1 [1,5,9,13]
 list 2 [2,6,10,14]
 llist 3 [3,7,11,15]
 l 4  [4,8,12,16]

How to achieve using scala

 input_list =      [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

 l 1 = input_list[0::4]
 l 2 = input_list[1::4]
 l 3 = input_list[2::4]
 l 4 = input_list[3::4]

In python I use this code but in Scala how we done this scale

4

There are 4 best solutions below

0
Gaël J On

There's no built-in operator to do this.

One way is to use zipWithIndex and filter with collect:

input
  .zipWithIndex
  .collect { case (value, index) if index % 2 == 0 => value
  }
0
Mateusz Kubuszok On

If your use case is only a sequence of increasing integers (perhaps with some step), there is Range:

1 to 16         // 1, 2, 3, ..., 15, 16
1 until 16      // 1, 2, 3, ..., 14, 15
1 to 17 by 2    // 1, 3, 5, ..., 15, 17
1 until 17 by 2 // 1, 3, 5, ..., 13, 15

However, you could combine that with your collection to extract values

val coll = List(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)
(1 to 17 by 2).flatMap(coll.lift).toList
0
Eastsun On

You can get it all in one line:

Welcome to Scala 2.13.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_312).
Type in expressions for evaluation. Or try :help.

scala> val input = List(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)
val input: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)

scala> val Seq(l1, l2, l3, l4) = input.sliding(4, 4).toList.transpose
val l1: List[Int] = List(1, 5, 9, 13)
val l2: List[Int] = List(2, 6, 10, 14)
val l3: List[Int] = List(3, 7, 11, 15)
val l4: List[Int] = List(4, 8, 12, 16)
0
Dima On

The closest you can get the python's slicing operators is probably by manipulating ranges:

val indexed = input_list.toIndexedSeq
val output = (0 until indexed.size by 4).map(indexed)