scala 如何获得 Seq 的第 n 个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36614214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the nth element of a Seq?
提问by Tom Wang
I want to get the nth element of a Seq, something like this:
我想获得 a 的第 n 个元素Seq,如下所示:
val mySeq = Seq("A", "B", "C")
mySeq.get(1) // Java syntax for List. This does not work.
采纳答案by Brian
mySeq.apply(1)is another way to say mySeq(1)
mySeq.apply(1)是另一种说法 mySeq(1)
scala> val mySeq = Seq("A", "B", "C")
mySeq: Seq[String] = List(A, B, C)
scala> mySeq(0)
res0: String = A
scala> mySeq(1)
res1: String = B
回答by elm
To avoid index out of bounds,
为了避免索引越界,
scala> mySeq(200)
java.lang.IndexOutOfBoundsException: 200
at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:65)
at scala.collection.immutable.List.apply(List.scala:84)
... 33 elided
lift the sequence,
提升序列,
mySeq.lift(2)
Some(C)
mySeq.lift(200)
None
or in a similar way,
或以类似的方式,
mySeq.drop(2).headOption
Some(C)
mySeq.drop(200).headOption
None
By lifting the sequence we define a partial function from Intonto each value of the sequence. Namely from each position index onto its corresponding value. Hence positions not defined (any negative value or larger than the size of the collection) are mapped onto None, the rest are defined and become Somevalue.
通过提升序列,我们从Int序列的每个值上定义了一个偏函数。即从每个位置索引到其对应的值。因此,未定义的位置(任何负值或大于集合的大小)被映射到None,其余的被定义并成为Some值。
回答by Tom Wang
The method to get the nth element of a Seqis apply:
获取a的第n个元素的方法Seq是apply:
val mySeq = Seq("A", "B", "C")
mySeq.apply(1) // "B"
Usually, you will never write x.apply(y)and just use shorthand x(y). The Scala compiler will convert it for you.
通常,您永远不会编写x.apply(y)而只会使用速记x(y)。Scala 编译器会为您进行转换。
mySeq(1) // "B"
To avoid potential index out of bounds, you can wrap using Try.
为避免潜在的索引越界,您可以使用Try.
Try(mySeq(x)).toOption
This will return Nonewhen x>= 3 and Some(...)when x< 3.
这将None在x>= 3 和< 3Some(...)时返回x。
回答by M.S.Visser
Further to Tom's answer, a specific use case where .apply() is necessary, is if you have an object which you just cast to a seq. In that case you cannot use (), since your object is not named. Here is an example:
除了汤姆的回答之外,一个需要 .apply() 的特定用例是,如果您有一个刚刚转换为 seq 的对象。在这种情况下,您不能使用 (),因为您的对象未命名。下面是一个例子:
println("Count of column test in MyDF is "+MyDF.groupBy().agg(count("test")).first.toSeq.apply(0));
Or, sticking to the example above:
或者,坚持上面的例子:
println("Second element of Seq(\"A\", \"B\", \"C\") is: "+Seq("A", "B", "C").apply(1));
Second element of Seq("A", "B", "C") is: B

