scala 如何在元组列表中找到最大值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15769366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find max in a list of tuples?
提问by Shakti
I have the following list of tuples:
我有以下元组列表:
val arr = List(('a',10),('b',2),('c',3))
How to find the tuple with the max key or max value?
如何找到具有最大键或最大值的元组?
The proper answer should be (c, 3)for max key lexicographically or ('a', 10)for max value.
正确的答案应该是(c, 3)按字典顺序使用 max key 或('a', 10)max value。
回答by om-nom-nom
Easy-peasy:
十分简单:
scala> val list = List(('a',10),('b',2),('c',3))
list: List[(Char, Int)] = List((a,10), (b,2), (c,3))
scala> val maxByKey = list.maxBy(_._1)
maxByKey: (Char, Int) = (c,3)
scala> val maxByVal = list.maxBy(_._2)
maxByVal: (Char, Int) = (a,10)
So basically you can provide to List[T]any function T => B(where Bcan be any ordered type, such as Intor Stringby example) that will be used to find the maximum.
因此,基本上您可以提供用于查找最大值的List[T]任何函数T => B(其中B可以是任何有序类型,例如Int或String示例)。
回答by Kevin Meredith
No doubt @om-nom-nomprovided a concise, correct answer. However, it will throw an exception for an empty list.
毫无疑问@ om-nom-nom提供了一个简洁、正确的答案。但是,它会为空列表抛出异常。
EDIT #2Given my first edit, it's worthwhile to re-write my original, flawed answer:
编辑 #2鉴于我的第一次编辑,重新编写我原来的、有缺陷的答案是值得的:
def max[A](list: List[(A, Int)]): Option[Int] = list match {
case Nil => None
case x :: xs => { val result = xs.foldLeft(x._2) { // acc = first item in list
(acc, elem) => if(elem._2 > acc) elem._2 else acc
}
Some(result)
}
}
Note: I'm guessing that scalazwould let you use a more generic Num-like type instead of Int, but I haven't worked with it at all.
注意:我猜scalaz会让你使用更通用Num的类型而不是Int,但我根本没有使用过它。
Testing
测试
scala> val list = List(('a',10),('b',2),('c',3))
list: List[(Char, Int)] = List((a,10), (b,2), (c,3))
scala> max(list)
res5: Option[Int] = Some(10)
scala> val list: List[(String, Int)] = Nil
list: List[(String, Int)] = List()
scala> max(list)
res6: Option[Int] = None
EDITFor picking a start value, I decided to edit my answer after talking with @DustinGetz.
编辑为了选择一个起始值,我决定在与 @ DustinGetz交谈后编辑我的答案。
Picking Int.MinValuemight not be a good choice as it's dependent on the particular OS/system on which the app is running.
选择Int.MinValue可能不是一个好的选择,因为它取决于运行应用程序的特定操作系统/系统。
I would argue that the first element in the list should be the start value. However, there's a potential run-time exception if the list is empty.
我认为列表中的第一个元素应该是起始值。但是,如果列表为空,则存在潜在的运行时异常。
Please take a look at this post for more discussion - https://stackoverflow.com/a/23184020/409976.
请查看这篇文章进行更多讨论 - https://stackoverflow.com/a/23184020/409976。
回答by Xavier Guihot
Starting Scala 2.13, a slightly safer solution (which handles empty lists) would consist in using maxByOption/minByOptionwhich returns Noneif the sequence is empty:
开始Scala 2.13,一个稍微更安全的解决方案(处理空列表)包括使用maxByOption/如果序列为空则minByOption返回None:
List(('a', 10),('b', 2),('c', 3)).maxByOption(_._1)
// Option[(Char, Int)] = Some((c,3))
List[(Char, Int)]().maxByOption(_._1)
// Option[(Char, Int)] = None
This way you could also decide to fallback on a default value when the list is empty:
通过这种方式,您还可以决定在列表为空时使用默认值:
List[(Char, Int)]().maxByOption(_._1).getOrElse(('a', 1))
// (Char, Int) = (a,1)

