我有一个列表,其中可能包含比较相等的元素。我想要一个类似的列表,但有一个元素被删除。因此,从(A,B,C,B,D)中,我希望能够只“删除”一个B,例如(A,C,B,D)。结果中元素的顺序并不重要。
我有可用的代码,是用Scala以Lisp启发的方式编写的。有没有一种更惯用的方式呢?
上下文是一个纸牌游戏,其中有两副标准纸牌在玩,所以可能有重复的纸牌,但仍然一次玩一张。
def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
if (Nil == right) {
return left
}
if (c == right.head) {
return left ::: right.tail
}
return removeOne(c, right.head :: left, right.tail)
}
def removeCard(c: Card, cards: List[Card]): List[Card] = {
return removeOne(c, Nil, cards)
}
发布于 2011-04-13 03:47:32
我在上面的答案中没有看到这种可能性,所以:
scala> def remove(num: Int, list: List[Int]) = list diff List(num)
remove: (num: Int,list: List[Int])List[Int]
scala> remove(2,List(1,2,3,4,5))
res2: List[Int] = List(1, 3, 4, 5)
编辑:
scala> remove(2,List(2,2,2))
res0: List[Int] = List(2, 2)
就像一个护身符:-)。
发布于 2013-06-28 02:30:33
您可以使用filterNot
方法。
val data = "test"
list = List("this", "is", "a", "test")
list.filterNot(elm => elm == data)
发布于 2011-04-12 22:53:08
你可以试试这个:
scala> val (left,right) = List(1,2,3,2,4).span(_ != 2)
left: List[Int] = List(1)
right: List[Int] = List(2, 3, 2, 4)
scala> left ::: right.tail
res7: List[Int] = List(1, 3, 2, 4)
和as方法:
def removeInt(i: Int, li: List[Int]) = {
val (left, right) = li.span(_ != i)
left ::: right.drop(1)
}
https://stackoverflow.com/questions/5636717
复制相似问题