Scala快速入門
阿新 • • 發佈:2018-12-23
判斷是否為空
cars.isEmpty
取第一個元素
cars.head
取第一個元素外的元素列表
cars.tail
cars.reverse.init
init取最後一個元素外的元素列表
cars.init
cars.reverse.tail
取最後一個
cars:last
取第二個元素
cars.tail.head
取倒數第二個元素
cars.init.last
元素倒置
cars.reverse
丟棄前N個元素,返回元素列表
cars drop 1
獲取前幾個元素列表
cars take 2
cars.take(2)
將列表進行分割,從Index N的位置進行分割,返回前後兩個元素列表,位置N算後面的元素列表
cars.splitAt(1)
(cars.take(1),cars.drop1)
zip 返回的是List型別的元組(Tuple)
scala> val arr = List("1","6","3","5","9") arr: List[String] = List(1, 6, 3, 5, 9) scala> val num = List(1,6,3,5,9) num: List[Int] = List(1, 6, 3, 5, 9) scala> arr zip num res99: List[(String, Int)] = List((1,1), (6,6), (3,3), (5,5), (9,9))
插入排序演算法
def sort(xs:List[Int]) :List[Int] ={ if(xs.isEmpty) Nil else insert(xs.head, sort(xs.tail)) } def insert(x:Int, xs:List[Int]) :List[Int] ={ if(xs.isEmpty || x<= xs.head) x:: xs else xs.head :: insert(x,xs.tail) }
List連線操作 :::
scala> List(1,2):::List(3,4) res35: List[Int] = List(1, 2, 3, 4)
list相等判斷
val arr = List(1,6,3,5,9) val arr1 = List("1","6","3","5","9") aaa == arr1 //false val arr = List("1","6","3","5","9") val arr1 = List("1","6","3","5","9") arr == arr1 //true
range方法,構建某一值範圍內的List
val nums = List.range(2,9)
range主法,指定步長N,範圍不存在的返回空List
val nums = List.range(2,100, 5)
val nums = List.range(100,20, -5)
flatten,將列表平滑成第一個元素
scala> List(List("aaa","bbb"),List("111","222")).flatten res34: List[String] = List(aaa, bbb, 111, 222)
concat列表連結
scala> List.concat(List("aaa","bbb"),List("111","222")) res32: List[String] = List(aaa, bbb, 111, 222) \\