2013-09-21 111 views

回答

9

正如Hiura说,还是这样的:

object ListDemo extends App { 
    val lst = List(1, 2, 3) 
    println(lst(0)) // Prints specific value. In this case 1. 
        // Number at 0 position. 
    println(lst(1)) // Prints 2. 
    println(lst(2)) // Prints 3. 
} 
9

基本上,你的Python代码等同的:(在斯卡拉解释器中运行)

scala> val l = 1 :: 2 :: 3 :: 4 :: Nil 
l: List[Int] = List(1, 2, 3, 4) 

scala> val one = l.head 
one: Int = 1 

scala> println(one) 
1 

Here是关于Scala的列表的文档。


它被要求作为附属问题“我如何显示每个元素?”。

这里是一个递归实现使用模式匹配:

scala> def recPrint(xs: List[Int]) { 
    | xs match { 
    |  case Nil => // nothing else to do 
    |  case head :: tail => 
    |   println(head) 
    |   recPrint(tail) 
    | }} 
recPrint: (xs: List[Int])Unit 

scala> recPrint(l) 
1 
2 
3 
4 

正如大卫·韦伯在评论中指出的,如果你不能使用递归算法来访问你的列表中的元素,那么你应该考虑使用其他的容器,因为访问List的第i个元素需要O(N)。

+0

耶找到,但我怎么能在列表打印第二个或第三个元素? –

+0

那么,那是另一个问题;-) 你可以使用'apply'方法(比如在Brano88的答案中),或者在列表的尾部递归。 – Hiura

+3

如果您可以从头到尾遍历列表,然后递归。如果没有,则使用错误的数据结构,因为适用于O(N)的列表。改用Vector或Array。 –

2

答案可以很容易地在scaladoc for list

def head: A 
Selects the first element of this list.