從Scala中的列表返回元素 (Returning an element from a List in Scala)


問題描述

從 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 boolean true/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 PagelsBinil ThomasTim SullivanDaniel SpiewaksblundyAlex Cruise)

參考文件

  1. Returning an element from a List in Scala (CC BY‑SA 2.5/3.0/4.0)

#list #scala






相關問題

Python 讀取 txt 文件作為輸入:IndexError: list index out of range? (Python read txt file as input: IndexError: list index out of range?)

danh sách trong python, vòng lặp for, mảng (list in python, loop for, array)

查找 pdfs/doc/docx/etc 的批處理文件 (Batch file to look for pdfs/doc/docx/etc)

如何在python中將所有負數更改為零? (How do I change all negative numbers to zero in python?)

從Scala中的列表返回元素 (Returning an element from a List in Scala)

如何在共享點列表中指定定義的排序 (How do you specify a defined sort in sharepoint list)

在 Mathematica 中將列表元素連接成一個數字 (Concatenate list elements into a number in Mathematica)

如何從 javascript 對像中獲取名稱和值到新列表中? (How to get name and values from a javascript object into a new list?)

Kivy:如何使用 RecycleView 在 Kivy 中顯示具有可變行的列表? (Kivy: how to display a list with variable rows in Kivy with a RecycleView?)

無法正確對齊列表中的中間文本 (Can't get middle text in list aligned correctly)

在 Python 列表中查找位於特定字符串之間的字符串 (Find Strings Located Between Specific Strings in List Python)

有沒有辦法在 Python 中使用變量中的字符串調用方法? (Is there a way to call a method in Python using a string inside a variable?)







留言討論