gpt4 book ai didi

list - 如何在scala中按周将列表分成组

转载 作者:行者123 更新时间:2023-12-04 23:21:32 25 4
gpt4 key购买 nike

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,4,5,6)
Group 3: (0,1,2,3,4,5,6)
...
last Group:(0,1,2)

最佳答案

Scala 的集合非常强大,这应该在几行中完成:

val (firstWeek, nextWeeks) = data.span(_.dayOfWeek != 0)
val weeks = (firstWeek :: nextWeeks.grouped(7).toList).dropWhile(_.isEmpty)

查看 span 的文档和 grouped here .
println(weeks.zipWithIndex.map {
case (week, i) => s"Group $i: (${week.map(_.dayOfWeek).mkString(",")})"
}.mkString("\n"))

输出:
Group 0: (3,4,5,6)
Group 1: (0,1,2,3,4,5,6)
Group 2: (0,1,2,3,4,5,6)
[snip]
Group 12: (0,1,2,3,4,5,6)
Group 13: (0,1,2,3,4,5,6)
Group 14: (0,1,2)

关于list - 如何在scala中按周将列表分成组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24924409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com