問題描述
從 Scala 中的 List 返回一個元素 (Returning an element from a List in Scala)
我最近一直在從事 Scala 的初學者項目,並且有一個關於 Scala 列表的初學者問題。
假設我有一個元組列表( List[Tuple2[String, String ]]
,例如)。是否有一種方便的方法可以從 List 中返回指定元組的第一次出現,還是需要手動遍歷列表?
參考解法
方法 1:
scala> val list = List(("A", "B", 1), ("C", "D", 1), ("E", "F", 1), ("C", "D", 2), ("G", "H", 1))
list: List[(java.lang.String, java.lang.String, Int)] = List((A,B,1), (C,D,1), (E,F,1), (C,D,2), (G,H,1))scala> list find {e => e._1 == "C" && e._2 == "D"}
res0: Option[(java.lang.String, java.lang.String, Int)] = Some((C,D,1))
</pre>方法 2:
You could try using find. (Updated scala‑doc location of find)
方法 3:
As mentioned in a previous comment,
find
is probably the easiest way to do this. There are actually three different "linear search" methods in Scala's collections, each returning a slightly different value. Which one you use depends upon what you need the data for. For example, do you need an index, or do you just need a booleantrue
/false
?方法 4:
If you're learning scala, I'd take a good look at the Seq trait. It provides the basis for much of scala's functional goodness.
方法 5:
You could also do this, which doesn't require knowing the field names in the Tuple2 class‑‑it uses pattern matching instead:
list find { case (x,y,_) => x == "C" && y == "D" }
"find" is good when you know you only need one; if you want to find all matching elements you could either use "filter" or the equivalent sugary for comprehension:
for ( (x,y,z) <‑ list if x == "C" && y == "D") yield (x,y,z)
(by Max Pagels、Binil Thomas、Tim Sullivan、Daniel Spiewak、sblundy、Alex Cruise)
參考文件