如何在scala中按周拆分列表
发布时间:2020-12-16 09:50:28 所属栏目:安全 来源:网络整理
导读:case class Test(dayOfWeek:Int,b:Int=Random.nextInt)val data=(3 to 100).map(_ % 7).map(Test(_)) 如何将数据分成组,每组有一周的数据,如果一周没有完成,也有一组.所以小组应该是 Group 1: (3,4,5,6) // the number here is the dayOfWeekGroup 2: (0,1,2
case class Test(dayOfWeek:Int,b:Int=Random.nextInt) val data=(3 to 100).map(_ % 7).map(Test(_)) 如何将数据分成组,每组有一周的数据,如果一周没有完成,也有一组.所以小组应该是 Group 1: (3,4,5,6) // the number here is the dayOfWeek Group 2: (0,1,2,3,6) Group 3: (0,6) ... last Group:(0,2) 解决方法
Scala的集合非常强大,这应该在几行中完成:
val (firstWeek,nextWeeks) = data.span(_.dayOfWeek != 0) val weeks = (firstWeek :: nextWeeks.grouped(7).toList).dropWhile(_.isEmpty) 查看span的doc并将其分组为here. println(weeks.zipWithIndex.map { case (week,i) => s"Group $i: (${week.map(_.dayOfWeek).mkString(",")})" }.mkString("n")) 输出: Group 0: (3,6) Group 1: (0,6) Group 2: (0,6) [snip] Group 12: (0,6) Group 13: (0,6) Group 14: (0,2) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |