[英]Scala: Removing key/value pair from list
再次,我坚持使用Scala和键/值对的想法。 同样,我想以某种方式使用Option。 这次,我停留在如何基于其密钥以及仅该密钥的第一个实例(并非全部)的基础上删除一对。 我试图使用filter
和filterNot
但这会删除共享同一密钥的所有对。 另外,再次尝试仅使用List
来实现它,以使其半简单
很难说出您的要求。 如果您将要编写的函数的签名写出来,这将有所帮助。
大概是这样吗?
def remove[A, B](seq: Seq[(A, B)], key: A): Seq[(A, B)] =
seq.indexWhere(_._1 == key) match {
case -1 => seq
case n => seq.patch(n, Nil, 1)
}
remove(Seq((1,2), (2,3), (3,4), (2,5)), 2)
// List((1,2), (3,4), (2,5))
remove(Seq((1,2), (2,3), (3,4), (2,5)), 6)
// List((1,2), (2,3), (3,4), (2,5))
Seq有一个名为find
的方法 ,它可以完全满足您的要求:
def find(p: (A) ⇒ Boolean): Option[A] Finds the first element of the sequence satisfying a predicate, if any. Note: may not terminate for infinite-sized collections. p the predicate used to test elements. returns an option value containing the first element in the sequence that satisfies p, or None if none exists.
用法:
val list = List(("A",1),("B",2),("C",3))
def remove(key:String): Option[Int] = list.find(_._1 == key)
remove("B")
// Some((B,2))
remove("D")
// None
val list = List(1 -> 'a, 2 -> 'b, 2 -> 'c)
val removal = list find (_._1 == 2)
// Option[(Int, Symbol)] = Some((2,'b))
val newList = list diff removal.toList
// List[(Int, Symbol)] = List((1,'a), (2,'c))
diff
将仅删除在参数列表中找到的每个元素的第一个实例,而不是像filter
一样全部删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.