[英]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.