如何在Scala中的List中找到最大值的索引?

时间:2012-12-23 13:05:26

标签: scala indexing max scala-collections

对于Scala List [Int],我可以调用max方法来查找最大元素值。

如何找到最大元素的索引?

这就是我现在正在做的事情:

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

6 个答案:

答案 0 :(得分:38)

执行此操作的一种方法是使用索引压缩列表,找到具有最大第一个元素的结果对,并返回该对的第二个元素:

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

这不是解决问题的最有效方法,但它是惯用且清晰的。

答案 1 :(得分:9)

由于Seq是Scala中的函数,因此以下代码有效:

list.indices.maxBy(list)

答案 2 :(得分:1)

更容易阅读:

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

答案 3 :(得分:1)

  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

如果有多个最大值,则返回第一个索引。

优点:您可以将它用于多种类型,它只通过列表一次,您可以提供默认索引而不是获取空列表的异常。

缺点:也许你更喜欢例外:)不是一个单行。

答案 4 :(得分:1)

我认为这里提供的大多数解决方案都通过列表两次(或平均 1.5 次)——一次是最大位置,另一个是最大位置。也许很多注意力都集中在看起来漂亮的东西上?

为了只遍历一次非空列表,可以尝试以下方法:

list.foldLeft((0, Int.MinValue, -1)) {
    case ((i, max, maxloc), v) => 
        if (v > max) (i + 1, v, i)
        else (i + 1, max, maxloc)}._3

答案 5 :(得分:0)

皮普我的图书馆! :)

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)

此处有关此模式的更多详细信息:http://www.artima.com/weblogs/viewpost.jsp?thread=179766

相关问题