【问题标题】:scala for every first element in a list of tuples get max of the second element元组列表中每个第一个元素的scala获取第二个元素的最大值
【发布时间】:2017-08-30 08:05:21
【问题描述】:

我有一个元组列表,如下所示

List((a,1), (a,2), (b,2), (b,1)) 

我想从上面的列表中创建一个如下列表

List((a,2), (b,2))

只有一个第一个元素和 MAX 个第二个元素。我怎样才能简洁地做到这一点?

【问题讨论】:

  • 试试这个 list.groupBy(._1).map { case (common, lst) => (common, lst.reduce( max _)) }
  • 那么,你在尝试的时候遇到了什么问题?
  • @Dima 在我输入完整评论之前按下回车键。这是我尝试错误时得到的结果:value max is not a member of (String, Int)
  • 这行得通 myList.groupBy(._1).map {case (common, lst) => lst.maxBy(._2) }.toList

标签: scala list unique


【解决方案1】:

由于您只需要一次相同值的第一个元素以及相应的第二个元素的最大值,因此将问题改写为for every distinct 1st element in the tuple list, list the max 2nd element 没有区别:

val l = List(("a",1), ("a",2), ("b",2), ("b",1))

l.groupBy(_._1).
  mapValues( _.map(_._2).max ).
  toList
// res1: List[(String, Int)] = List((b,2), (a,2))

【讨论】:

  • 完美。更好。
猜你喜欢
  • 1970-01-01
  • 2019-05-20
  • 1970-01-01
  • 2022-10-21
  • 2019-04-19
  • 2011-02-17
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多