访问列表中的下一个元素以在Scala中进行比较

时间:2011-04-20 07:14:49

标签: list scala

我是Scala的新手,我想知道如何调用列表的下一个元素,因为我试图将当前元素与相邻元素进行比较。 给定x作为当前元素,我尝试类似于java,x + 1但是没有用。有什么帮助吗?

for (x <- list; if (x == (next adj. element))) println("same")

8 个答案:

答案 0 :(得分:29)

滑动怎么样?

val list = List(1,2,3,4)
list.sliding(2).foreach(println)

//List(1, 2)
//List(2, 3)
//List(3, 4)

答案 1 :(得分:7)

for循环中执行此操作的规范方法是:

scala> val xs = List(1,2,3,4,3,2)
xs: List[Int] = List(1, 2, 3, 4, 3, 2)

scala> for (List(left,right) <- xs.sliding(2) if (left < right)) println(left + " < " + right)
1 < 2
2 < 3
3 < 4

scala> for ((left,right) <- (xs zip xs.tail) if (left < right)) println(left + " < " + right)
1 < 2
2 < 3
3 < 4

(顺便说一下,你可能最好把if语句放在外面而不是在这个例子中的for comprehension中。)

如果你有索引而不是值,你只需使用相同的模式取消引用它们。就个人而言,我没有发现这种模式非常清楚或有用。它很慢,有一些奇怪的角落案例,列表不完整,并且很难跟踪正在发生的事情。相反,我定义

class PairedIterable[A](it: Iterable[A]) {
  def foreachpair(f: (A,A) => Unit) = {
    val i = it.iterator
    if (i.hasNext) {
      var prev = i.next
      while (!ans && i.hasNext) {
        val x = i.next
        f(prev,x)
        prev = x
      }
    }
  }
}
implicit def iterable_has_pairs[A](it: Iterable[A]) = new PairedIterable(it)

然后可以这样使用:

scala> xs.foreachpair((left, right) => if (left < right) println(left + " < " + right))
1 < 2
2 < 3
3 < 4

变体“forallpair”,“existspair”和“findpair”特别有用。

答案 2 :(得分:3)

通过递归列表可以更好地处理,而不是遍历元素,因为元素对列表一无所知。

例如:

def recurse[T](list: List[T]): Unit = list match {
    case List(x, y, _*) if x == y => 
        println("same")
        recurse(list.tail)
    case Nil =>
    case _   => recurse(list.tail)
}

答案 3 :(得分:2)

作为一种选择,您可以使用match和递归而不是for

object Test {
  def main(args: Array[String]) {
    val list = List(1, 5, 3)
    loop(list)
  }

  def loop(list: List[Int]) {
    list match {
      case Nil => println("Empty list")
      case x :: Nil => println("last " + x)
      case x :: tail => {
        println(x + " - " + tail.head)
        loop(tail)
      }

    }
  }
}

答案 4 :(得分:2)

scala> val xs = 1::3::5::4::Nil
xs: List[Int] = List(1, 3, 5, 4)

scala> (xs, xs.tail).zip.foreach(println)
(1,3)
(3,5)
(5,4)

scala>

答案 5 :(得分:0)

scala> val li = List (3, 4, 5) 
li: List[Int] = List(3, 4, 5)

scala> li.tail.head 
res74: Int = 4

答案 6 :(得分:0)

list.tail.head

如果要浏览列表前面的所有元素,

会给出下一个元素。这是因为头部是最前面的元素,尾部是列表的其余部分。

答案 7 :(得分:0)

与Scala 2.11.7中一样,以下内容有效:

scala> val xs = List(1,2,3,4)
xs: List[Int] = List(1, 2, 3, 4)

1)拉尾巴

scala> xs.zip(xs.tail)
res0: List[(Int, Int)] = List((1,2), (2,3), (3,4))

2)滑动窗口

scala> xs.sliding(2)
res1: Iterator[List[Int]] = non-empty iterator
相关问题