如何用Scala实现类似Python的按步长切片拆分列表?
Scala实现按固定步长拆分列表
给定输入列表:
val inputList = List(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16)
要拆分成四个子列表[1,5,9,13]、[2,6,10,14]、[3,7,11,15]、[4,8,12,16],有两种常用实现方式:
方法一:按索引分组
通过zipWithIndex给元素绑定索引,按索引对4取余的结果分组,再提取元素值:
// 先按索引模4分组 val groups = inputList.zipWithIndex.groupBy { case (_, idx) => idx % 4 } // 提取各组元素 val l1 = groups(0).map(_._1).toList val l2 = groups(1).map(_._1).toList val l3 = groups(2).map(_._1).toList val l4 = groups(3).map(_._1).toList
如果想一次性获取四个列表,可以排序后解构:
val (l1, l2, l3, l4) = { val sortedGroups = inputList.zipWithIndex .groupBy(_._2 % 4) .toList .sortBy(_._1) // 按分组键排序,保证顺序正确 .map(_._2.map(_._1)) (sortedGroups(0), sortedGroups(1), sortedGroups(2), sortedGroups(3)) }
方法二:模拟Python步长切片
和Python的input_list[start::4]逻辑完全对应,通过遍历指定起始索引+步长的序列来取值:
val l1 = (0 until inputList.length by 4).map(inputList(_)).toList val l2 = (1 until inputList.length by 4).map(inputList(_)).toList val l3 = (2 until inputList.length by 4).map(inputList(_)).toList val l4 = (3 until inputList.length by 4).map(inputList(_)).toList
这种方式和Python的写法逻辑一致,直观易懂。
内容的提问来源于stack exchange,提问作者Arun Kumar
相关产品推荐
相关产品推荐

