2015-06-29 60 views
0

正如我在标题中指出的那样,如何比较索引N的元素与索引N + 1的元素,如果比较的元素完全相同,则yield元素只有一次。 我知道我可以使用toSet来获得一组独特的元素,但是这并不能帮助我,因为我的列表可以包含重复的元素,但重复的元素不能成为我列表中的下一个元素。如何将列表元素与下一个元素进行比较以生成此元素?

val ll = List(1, 2, 3, 6, 3, 7, 5, 5, 6, 3) 
// Desired output: List(1, 2, 3, 6, 3, 7, 5, 6, 3) 

我得到了一个“附近工作的解决方案”使用zipWithIndex.collect,但是当我比较里面,指数运行OutOfBounds。我可以使这个工作,如果我可以使用两个条件里面,首先检查最大索引是索引=(list.size-1),然后我可以比较列表(索引)!=列表(索引+ 1),然后收益列表(索引)

什么我都没有(因为OutOfBounds)的成功尝试,是:

times.zipWithIndex.collect 
{ 
    case (element, index) 
     // index+1 will be incremented out of my list 
     if (times(index) != times(index+1)) => times(index) 
} 

这可以工作,如果我可以用一个条件限制指数,但不会有两个条件下工作:

times.zipWithIndex.collect 
{ 
    case (element, index) 
     if (index < times.size) 
      if (times(index) != times(index+1)) => times(index) 
} 

我很欣赏任何一种选择。

+1

我一直不解,为什么Scala的集合库没有这种分组功能。在Haskell中,你可以把它写成'map head $ group ll'。 –

+0

@ChrisMartin你的意思是'map head $ group ll'是完整的代码,并会给出所需的输出?我很好奇...... – bjfletcher

+0

@bjfletcher是啊:)重组是由'group'完成的,它将'[1,2,3,6,3,7,5,5,6,3]'变成' [[1],[2],[3],[6],[3],[7],[5,5],[6],[3]]'。 –

回答

1

您可以使用zip自己的列表,删除第一个元素,以便比较索引N处的元素和N + 1。您只需要追加最后一个元素(您可能希望使用ListBuffer作为追加最后一个元素元素需要复制列表)。

val r = times.zip(times.drop(1)).withFilter(t => t._1 != t._2).map(_._1) :+ times.last 

scala> val times = List(1, 2, 3, 6, 3, 7, 5, 5, 6, 3) 
times: List[Int] = List(1, 2, 3, 6, 3, 7, 5, 5, 6, 3) 

scala> val r = times.zip(times.drop(1)).withFilter(t => t._1 != t._2).map(_._1) :+ times.last 
r: List[Int] = List(1, 2, 3, 6, 3, 7, 5, 6, 3) 
+0

这将输出一个“怪胎”结果为: 向量(L,i,s,t,: ,L,i,s,t,(,1,,, 2,,, 3,,, 6,,, 3,,, 7,,, 5,,, 6) ,3; Size:10) – LXSoft

+0

@LXSoft我已经在您的输入上测试过它,并且我得到了预期的输出。 –

+0

val L:列表[Int] =列表(1,2,3,6,3,7,5,5,6,3) println(“List:”+ L.zip(L.drop(1 ))。withFilter(t => t._1!= t._2).map(_._ 1):+ L.last +“; Size:”+ L.zip(times.drop(1))。withFilter(t => t._1!= t._2).map(_._ 1).size) 结果与第一条评论相同。 – LXSoft

2

怎么样

ll.foldLeft(List[Int]())((acc, x) => acc match {case Nil => List(x) case y => if (y.last == x) y else y :+ x}) 
1

下面是使用滑动功能,我的选择:

val ll = List(1, 2, 3, 6, 3, 7, 5, 5, 6, 3) 
ll.sliding(2) 
    .filter(t => t.length > 1 && t(0) != t(1)) 
    .map(t => t(0)) 
    .toList :+ ll.last 
相关问题