Scala List 操作 list中最大數的下標 Vector轉List
阿新 • • 發佈:2019-01-29
1.List操作
take takeRight takeWhile
val nums = List(1,1,1,1,4,4,4,4)
val left = nums.take(4) //List(1,1,1,1)
val right = nums.takeRight(4) //List(4,4,4,4)
val headNums = nums.takeWhile(_==nums.head) //List(1,1,1,1)
drop dropRight dropWhile
val nums = List(1,2,3,4,5,6,7,8)
val left = nums.drop(3 ) //List(4,5,6,7,8)
val right = nums.dropRight(3) //List(1,2,3,4,5)
val tailNums = nums.dropWhile(_==nums.head) //List(2,3,4,5,6,7,8)
indexOf indexWhere
scala> val lst = List("question?mark")
lst: List[String] = List(question?mark)
scala> lst.indexOf('?')
res2: Int = -1
//列表lst中只有一個元素"question?mark" ,不等於"?",所以indexOf('?')沒找到匹配項,返回-1
//可以用
scala> lst.indexWhere(_.contains("?"))
res3:Int = 0
scala> lst(0).indexOf('?')
res4: Int = 8
scala> "where is ?".indexOf('?')
res5: Int = 9
scala> val lst = List("question?mark","where?","hello","why?")
lst: List[String] = List(question?mark, where?, hello, why?)
scala> lst.map (_.indexOf('?'))
res6: List[Int] = List(8, 5, -1, 3)
2.找出list中最大的數的下標
scala> List(0, 43, 1, 34, 10).zipWithIndex.maxBy(_._1)._2
res0: Int = 1
3.Vector轉List
定義一個方法:輸入一個Vector,輸出一個List,List的元素和Vector的元素相同。
List在Scala中是不可變的(immutable),改變一個List(的長度之類)事實上是yield一個List的新例項。
List的map方法不改變the container,只改變包含的values。
val v = Vector(1,2,3)
v:scala.collection.immutable.Vector[Int] = Vector(1,2,3)
v.toList
res0:List[Int] = List(1,2,3)
//或者:
List(Vector(1,2,3):_*)