在 Scala 中获取列表中的项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4981689/
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
Get item in the list in Scala?
提问by Andriy Drozdyuk
How in the world do you get just an element at index ifrom the List in scala?
在 Scala 中,如何从 List 中的索引i处获取一个元素?
I tried get(i), and [i]- nothing works. Googling only returns how to "find" an element in the list. But I already know the index of the element!
我试过get(i),并且 [i]- 没有任何效果。谷歌搜索只返回如何“找到”列表中的元素。但是我已经知道元素的索引了!
Here is the code that does not compile:
这是无法编译的代码:
def buildTree(data: List[Data2D]):Node ={
if(data.length == 1){
var point:Data2D = data[0] //Nope - does not work
}
return null
}
Looking at the List apidoes not help, as my eyes just cross.
查看List api无济于事,因为我的眼睛只是交叉。
回答by Rex Kerr
Use parentheses:
使用括号:
data(2)
But you don't really want to do that with lists very often, since linked lists take time to traverse. If you want to index into a collection, use Vector(immutable) or ArrayBuffer(mutable) or possibly Array(which is just a Java array, except again you index into it with (i)instead of [i]).
但是你真的不想经常对列表这样做,因为链表需要时间来遍历。如果要索引到集合中,请使用Vector(immutable) 或ArrayBuffer(mutable) 或可能Array(这只是一个 Java 数组,除非您再次使用(i)代替对其进行索引[i])。
回答by adamnfish
Safer is to use liftso you can extract the value if it exists and fail gracefully if it does not.
使用更安全,lift因此您可以提取存在的值,如果不存在则正常失败。
data.lift(2)
This will return None if the list isn't long enough to provide that element, and Some(value) if it is.
如果列表的长度不足以提供该元素,这将返回 None,如果是,则返回 Some(value)。
scala> val l = List("a", "b", "c")
scala> l.lift(1)
Some("b")
scala> l.lift(5)
None
Whenever you're performing an operation that may fail in this way it's great to use an Option and get the type system to help make sure you are handling the case where the element doesn't exist.
每当您执行可能以这种方式失败的操作时,最好使用 Option 并获取类型系统来帮助确保您处理元素不存在的情况。
Explanation:
解释:
This works because List's apply(which sugars to just parentheses, e.g. l(index)) is like a partial function that is defined wherever the list has an element. The List.liftmethod turns the partial applyfunction (a function that is only defined for some inputs) into a normal function (defined for any input) by basically wrapping the result in an Option.
这是有效的,因为 List 的apply(它只是括号,例如l(index))就像一个偏函数,它在列表有元素的地方定义。该List.lift方法apply通过将结果基本上包装在 Option 中,将偏函数(仅为某些输入定义的函数)转换为普通函数(为任何输入定义)。
回答by B.Mr.W.
Why parentheses?
为什么要括号?
Here is the quote from the book programming in scala.
这是书中引用的scala 编程。
Another important idea illustrated by this example will give you insight into why arrays are accessed with parentheses in Scala. Scala has fewer special cases than Java. Arrays are simply instances of classes like any other class in Scala. When you apply parentheses surrounding one or more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. So greetStrings(i) gets transformed into greetStrings.apply(i). Thus accessing an element of an array in Scala is simply a method call like any other. This principle is not restricted to arrays: any application of an object to some arguments in parentheses will be transformed to an apply method call. Of course this will compile only if that type of object actually defines an apply method. So it's not a special case; it's a general rule.
此示例说明的另一个重要思想将使您深入了解为什么在 Scala 中使用括号访问数组。Scala 的特殊情况比 Java 少。数组只是类的实例,就像 Scala 中的任何其他类一样。当您将一个或多个值周围的括号应用于变量时,Scala 会将代码转换为对该变量名为 apply 的方法的调用。所以greetStrings(i) 被转化为greetStrings.apply(i)。因此,在 Scala 中访问数组元素与其他任何方法一样只是一个方法调用。这个原则不限于数组:对象对括号中的某些参数的任何应用都将转换为应用方法调用。当然,只有当该类型的对象实际定义了一个 apply 方法时才会编译。所以这不是一个特例;这是一般规则。
Here are a few examples how to pull certain element (first elem in this case) using functional programming style.
以下是一些如何使用函数式编程风格拉取特定元素(在本例中为第一个元素)的示例。
// Create a multdimension Array
scala> val a = Array.ofDim[String](2, 3)
a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))
scala> a(0) = Array("1","2","3")
scala> a(1) = Array("4", "5", "6")
scala> a
Array[Array[String]] = Array(Array(1, 2, 3), Array(4, 5, 6))
// 1. paratheses
scala> a.map(_(0))
Array[String] = Array(1, 4)
// 2. apply
scala> a.map(_.apply(0))
Array[String] = Array(1, 4)
// 3. function literal
scala> a.map(a => a(0))
Array[String] = Array(1, 4)
// 4. lift
scala> a.map(_.lift(0))
Array[Option[String]] = Array(Some(1), Some(4))
// 5. head or last
scala> a.map(_.head)
Array[String] = Array(1, 4)
回答by Deepan Chakravarthi
Please use parenthesis () to access the list elements list_name(index)
请使用括号 () 访问列表元素 list_name(index)
回答by gun
This is the preferred way to access data of a List via index nowadays:
这是当今通过索引访问列表数据的首选方式:
scala> val list = List("a","b","c")
scala> list.get(1)
Some("b")
scala> list.get(5)
None
But like Rex Kerr metioned above: If you are using indexes, you should consider to use Vector instead of a List.
但是就像上面提到的 Rex Kerr 一样:如果您正在使用索引,您应该考虑使用 Vector 而不是 List。

