2016-07-30 102 views
0

我有一個列表如何從另一個列表中刪除列表的每個實例?

val l = List(1,2,3,2,6,4,2,3,4,2,1,3,6,3,2) 

,我想刪除特定序列,如(2,3)

因此所需的輸出是每個實例...

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

什麼是最簡單的/在斯卡拉完成這個最習慣的方式?

我已經試過這樣做,到目前爲止..

l.sliding(2).filter{ _!=List(2,3) } 

但我想不出從那裏走,這使我想知道如果我在正確的軌道上。

+1

我甚至不確定這個問題是否明確。如果我有'List(1,2,1,2,1)'我該怎麼做,我想刪除序列'1,2,1'。我最終得到了「List(1,2)'還是'List(2,1)'? – Alec

+0

@ cricket_007我已更新我的問題 @Alec一般而言,您是正確的。在這個特定的例子中,我需要從左邊開始移除,然後移到右邊,所以在你的例子中,結果將是'List(2,1)' –

+0

感謝您的編輯,但是你要去哪裏從那裏?這不適合你嗎? –

回答

1

可以遍歷列表遞歸,在時間消耗來自列表中的一個的頭元件和積聚所需的一些分成一個結果列表,同時丟棄匹配不良序列。一個簡單的尾遞歸的例子可以這樣工作的:

@annotation.tailrec 
def filterList[A](list: List[A], acc: List[A] = Nil): List[A] = list match { 
    case 2 :: 3 :: tail => filterList(tail, acc) 
    case head :: tail => filterList(tail, head :: acc) 
    case Nil => acc.reverse 
} 

scala> val l = List(1,2,3,2,6,4,2,3,4,2,1,3,6,3,2) 
scala> filterList(l) 
res0: List[Int] = List(1, 2, 6, 4, 4, 2, 1, 3, 6, 3, 2) 

或者更一般地說,可以使用startsWith檢查的List開始與序列當前迭代要刪除。

@annotation.tailrec 
def filterList[A](list: List[A], subList: List[A], acc: List[A] = Nil): List[A] = list match { 
    case l if(list startsWith subList) => filterList(l.drop(subList.length), subList, acc) 
    case head :: tail => filterList(tail, subList, head :: acc) 
    case Nil => acc.reverse 
} 

scala> filterList(l, List(2, 3)) 
res4: List[Int] = List(1, 2, 6, 4, 4, 2, 1, 3, 6, 3, 2) 

如果性能問題,您可以使acc可變。

+0

感謝這個答案m-z,我需要這個尾遞歸的一個,不要在我的用例上破壞堆棧。 –

1
def stripFrom[A](lst: List[A], x: List[A]): List[A] = 
    if (lst.containsSlice(x) && x.length > 0) 
    stripFrom(lst.patch(lst.indexOfSlice(x), List(), x.length), x) 
    else lst 

概念證明:

scala> stripFrom(List(1,2,3,2,6,4,2,3,4,2,1,3,6,3,2), List(2,3)) 
res3: List[Int] = List(1, 2, 6, 4, 4, 2, 1, 3, 6, 3, 2) 

scala> stripFrom(List(1,2,3,2,6,4,2,3,4,2,1,3,6,3,2), List(4,2)) 
res4: List[Int] = List(1, 2, 3, 2, 6, 3, 1, 3, 6, 3, 2) 

scala> stripFrom(List(1,2,3,2,6,4,2,3,4,2,1,3,6,3,2), List(4,2,3,4)) 
res5: List[Int] = List(1, 2, 3, 2, 6, 2, 1, 3, 6, 3, 2) 

scala> stripFrom(List(1,2,3,2,6,4,2,3,4,2,1,3,6,3,2), List(2)) 
res6: List[Int] = List(1, 3, 6, 4, 3, 4, 1, 3, 6, 3) 
+0

注意,如果有很多'x'實例從'lst'中移除,這將會非常緩慢,因爲這個列表需要被多次遍歷,把它放在O(n^2)附近, 。 –

相關問題