【发布时间】:2025-12-18 14:45:01
【问题描述】:
什么是拆分列表的简短功能方式
List(1, 2, 3, 4, 5) into List((1,2), (2, 3), (3, 4), (4, 5))
【问题讨论】:
标签: scala functional-programming
什么是拆分列表的简短功能方式
List(1, 2, 3, 4, 5) into List((1,2), (2, 3), (3, 4), (4, 5))
【问题讨论】:
标签: scala functional-programming
(假设您不在乎嵌套对是列表而不是元组)
Scala 集合有一个sliding 窗口函数:
@ val lazyWindow = List(1, 2, 3, 4, 5).sliding(2)
lazyWindow: Iterator[List[Int]] = non-empty iterator
实现集合:
@ lazyWindow.toList
res1: List[List[Int]] = List(List(1, 2), List(2, 3), List(3, 4), List(4, 5))
你甚至可以做更多“有趣”的窗口,比如长度为 3 的窗口,但需要第 2 步:
@ List(1, 2, 3, 4, 5).sliding(3,2).toList
res2: List[List[Int]] = List(List(1, 2, 3), List(3, 4, 5))
【讨论】:
您可以zip 列表及其tail:
val list = List(1, 2, 3, 4, 5)
// list: List[Int] = List(1, 2, 3, 4, 5)
list zip list.tail
// res6: List[(Int, Int)] = List((1,2), (2,3), (3,4), (4,5))
【讨论】:
我一直是pattern matching 的忠实粉丝。所以你也可以这样做:
val list = List(1, 2, 3, 4, 5, 6)
def splitList(list: List[Int], result: List[(Int, Int)] = List()): List[(Int, Int)] = {
list match {
case Nil => result
case x :: Nil => result
case x1 :: x2 :: ls => splitList(x2 :: ls, result.:+(x1, x2))
}
}
splitList(list)
//List((1,2), (2,3), (3,4), (4,5), (5,6))
【讨论】: