2017-02-05 49 views

回答

3

你可以用它尾巴zip名单:

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)) 
5

(假设你不关心你的嵌套对是列表而不是元组)

斯卡拉集合有一个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)) 

你甚至可以做更多 “funcy” 窗口,像长度为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)) 
1

我一直都是一个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))