How can I find the index of the maximum value in a List in Scala?

拈花ヽ惹草 提交于 2019-12-04 16:38:55

问题


For a Scala List[Int] I can call the method max to find the maximum element value.

How can I find the index of the maximum element?

This is what I am doing now:

val max = list.max 
val index = list.indexOf(max)

回答1:


One way to do this is to zip the list with its indices, find the resulting pair with the largest first element, and return the second element of that pair:

scala> List(0, 43, 1, 34, 10).zipWithIndex.maxBy(_._1)._2
res0: Int = 1

This isn't the most efficient way to solve the problem, but it's idiomatic and clear.




回答2:


Since Seq is a function in Scala, the following code works:

list.indices.maxBy(list)



回答3:


even easier to read would be:

   val g = List(0, 43, 1, 34, 10)
   val g_index=g.indexOf(g.max)



回答4:


  def maxIndex[ T <% Ordered[T] ] (list : List[T]) : Option[Int] = list match {
    case Nil => None
    case head::tail => Some(
        tail.foldLeft((0, head, 0)){
            case ((indexOfMaximum, maximum, index), elem) =>
              if(elem > maximum) (index, elem, index + 1)
              else (indexOfMaximum, maximum, index + 1)
        }._1
    )
  }   //> maxIndex: [T](list: List[T])(implicit evidence$2: T => Ordered[T])Option[Int]


    maxIndex(Nil)                            //> res0: Option[Int] = None
    maxIndex(List(1,2,3,4,3))                //> res1: Option[Int] = Some(3)
    maxIndex(List("a","x","c","d","e"))      //> res2: Option[Int] = Some(1)

    maxIndex(Nil).getOrElse(-1)              //> res3: Int = -1
    maxIndex(List(1,2,3,4,3)).getOrElse(-1)  //> res4: Int = 3
    maxIndex(List(1,2,2,1)).getOrElse(-1)    //> res5: Int = 1

In case there are multiple maximums, it returns the first one's index.

Pros:You can use this with multiple types, it goes through the list only once, you can supply a default index instead of getting exception for empty lists.

Cons:Maybe you prefer exceptions :) Not a one-liner.




回答5:


Pimp my library! :)

class AwesomeList(list: List[Int]) {
  def getMaxIndex: Int = {
    val max = list.max
    list.indexOf(max)
  }
}

implicit def makeAwesomeList(xs: List[Int]) = new AwesomeList(xs)
                                              //> makeAwesomeList: (xs: List[Int])scalaconsole.scratchie1.AwesomeList

//Now we can do this:
List(4,2,7,1,5,6) getMaxIndex             //> res0: Int = 2

//And also this:
val myList = List(4,2,7,1,5,6)            //> myList  : List[Int] = List(4, 2, 7, 1, 5, 6)
myList getMaxIndex                        //> res1: Int = 2

//Regular list methods also work
myList filter (_%2==0)                    //> res2: List[Int] = List(4, 2, 6)

More details about this pattern here: http://www.artima.com/weblogs/viewpost.jsp?thread=179766



来源:https://stackoverflow.com/questions/14011181/how-can-i-find-the-index-of-the-maximum-value-in-a-list-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!