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
CodePudding user response:
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
}
CodePudding user response:
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