如何在元组列表中找到最大值? [英] How to find max in a list of tuples?

查看:79
本文介绍了如何在元组列表中找到最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下元组列表:

val arr = List(('a',10),('b',2),('c',3))

如何找到具有最大值键或最大值的元组?

How to find the tuple with the max key or max value?

正确的答案应该是 (c, 3) 对于最大键字典或 ('a', 10) 对于最大值.

The proper answer should be (c, 3) for max key lexicographically or ('a', 10) for max value.

推荐答案

Easy-peasy:

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)

所以基本上你可以向 List[T] 提供任何函数 T =>B(其中 B 可以是任何有序类型,例如 IntString),用于查找最大.

So basically you can provide to List[T] any function T => B (where B can be any ordered type, such as Int or String by example) that will be used to find the maximum.

这篇关于如何在元组列表中找到最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆