【发布时间】:2023-01-17 00:13:40
【问题描述】:
我正在尝试删除列表中 n 次出现(不是所有出现!)的给定元素。 我面临的问题是当我尝试分为两种情况时,列表包含或不包含给定元素。如标题中所述,我的 if 语句给我一个错误。我该如何解决这个问题?
我的代码
def removeN[A](xs: List[A], elem: A, n: Int) : List[A] = {
val elemCount = xs.groupBy(identity).mapValues(_.size)(elem)
if (xs.contains(elem) == false) xs
else if (elemCount == n) xs.filterNot(x => x == elem)
else {
val (left, right) = xs.span(_ != elem)
print(s"$left and $right")
left ::: right.tail
}
错误讯息
removeN(List(1,2,3,2,1), 0, 2)
java.util.NoSuchElementException: key not found: 0
at scala.collection.MapOps.default(Map.scala:274)
at scala.collection.MapOps.default$(Map.scala:273)
at scala.collection.AbstractMapView.default(MapView.scala:186)
at scala.collection.MapOps.apply(Map.scala:176)
at scala.collection.MapOps.apply$(Map.scala:175)
at scala.collection.AbstractMapView.apply(MapView.scala:186)
at removeN(<console>:3)
... 32 elided
测试用例 removeN(列表(1,2,3,2,1), 0, 2) // => 列表(1, 2, 3, 2, 1)
【问题讨论】:
-
是什么让你认为
contains抛出了它?堆栈上没有contains..
标签: scala