Scala:按顺序从列表元素创建元组列表

Scala: Creating a list of tuples from list elements sequentially

我是 Scala 的新手,所以这个问题可能很幼稚。

我有一个这样的列表 List[Int] = List(0, 3, 6, 12, 14, 15, 16, 17)。我正在尝试创建这样的列表 [(0,3),(3,6),(6,12)..] 等等。到目前为止,这是我尝试过的:

val l1= List(0, 3, 6, 12, 14, 15, 16, 17)
var l2=scala.collection.mutable.ListBuffer[(Int,Int)]()
l1.zipWithIndex.slice(0,l1.length-1).foreach(x=>{val newval=(x._1,l1(x._2+1)); l2+=newval})

这里有两个问题:

  1. 如果我不使用 val newval,即尝试使用 l1.zipWithIndex.slice(0,l1.length-1).foreach(x=>l2+=(x._1,l1(x._2+1))),编译器会说: <console>:10: error: type mismatch; found : Int required: (Int, Int) l1.zipWithIndex.slice(0,l1.length-1).foreach(x=>l2+=(x._1,l1(x._2+1)))。这是为什么?
  2. 如果没有可变列表缓冲区,有什么方法可以做到这一点?
  1. +=ListBuffer l2 上接受重复参数的方法。这意味着当你做这样的事情时:

    scala> var l2 = scala.collection.mutable.ListBuffer[(Int, Int)]()
    l2: scala.collection.mutable.ListBuffer[(Int, Int)] = ListBuffer()
    
    scala> l2 += (1, 2)
    <console>:9: error: type mismatch;
     found   : Int(1)
     required: (Int, Int)
                  l2 += (1, 2)
    

.. 当您尝试添加元组时,编译器认为您正在尝试将多个 Int 添加到 ListBuffer。您需要一组额外的括号。

 l1.zipWithIndex.slice(0,l1.length-1).foreach(x=> l2 += ((x._1,l1(x._2+1)) ))
  1. 您可以使用 sliding,这将在整个集合中创建一个 "sliding window" 到 return 特定组大小的列表列表,其中包含一个步骤默认大小为:

    scala> List(0, 3, 6, 12, 14, 15, 16, 17).sliding(2)
               .map { case List(a, b) => (a, b) }.toList
    res10: List[(Int, Int)] = List((0,3), (3,6), (6,12), (12,14), (14,15), (15,16), (16,17))
    

除了滑动,你还可以像下面这样滑动:

  val l1= List(0, 3, 6, 12, 14, 15, 16, 17)
  val l2 = l1.take(l1.size - 1).zip(l1.tail)

已更新

   l1.zip(l1.tail) works.