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]
如何使用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]
在python中我使用这个代码但在Scala中我们如何实现这个比例
你可以在一行中得到所有内容:
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)
最接近python的切片操作符可能是通过操作范围:
val indexed = input_list.toIndexedSeq
val output = (0 until indexed.size by 4).map(indexed)
没有内置的操作符。
一种方法是使用zipWithIndex
和collect
过滤器:
input
.zipWithIndex
.collect { case (value, index) if index % 2 == 0 => value
}
如果你的用例只是一个递增的整数序列(可能有一些步骤),有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
但是,您可以将它与您的集合组合以提取值
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