【问题标题】:Better and efficient way to group list of tuples2 in scala在scala中对tuples2列表进行分组的更好和有效的方法
【发布时间】:2014-03-02 08:37:49
【问题描述】:

我有 Scala Tuples2 的列表,我必须将它们分组。我目前使用以下方式来执行它。

var matches:List[Tuple2[String,Int]]
var m = matches.toSeq.groupBy(i=>i._1).map(t=>(t._1,t._2)).toSeq.sortWith(_._2.size>_._2.size).sortWith(_._2.size>_._2.size)

上面的分组给了我 Seq[(String,Seq[(String,Int)])] 但我想拥有 Seq[(String,Seq[Int])]

我想知道有没有更好更有效的方法。

【问题讨论】:

  • 一个预期行为的例子会很有帮助。

标签: scala group-by grouping scala-collections


【解决方案1】:

首先,一些想法:

// You should use `val` instead of `var`
var matches: List[Tuple2[String, Int]] = List("a" -> 1, "a" -> 2, "b" -> 3, "c" -> 4, "c" -> 5)
var m = matches
  .toSeq                            // This isn't necessary: it's already a Seq
  .groupBy(i => i._1)
  .map(t => (t._1, t._2))           // This isn't doing anything at all
  .toSeq
  .sortWith(_._2.size > _._2.size)  // `sortBy` will reduce redundancy
  .sortWith(_._2.size > _._2.size)  // Not sure why you have this twice since clearly the 
                                    // second sorting isn't doing anything...

所以试试这个:

val matches: List[Tuple2[String, Int]] = List("a" -> 1, "a" -> 2, "b" -> 3, "c" -> 4, "c" -> 5)
val m: Seq[(String, Seq[Int])] = 
  matches
    .groupBy(_._1)
    .map { case (k, vs) => k -> vs.map(_._2) }  // Drop the String part of the value
    .toVector
    .sortBy(_._2.size)
println(m) // Vector((b,List(3)), (a,List(1, 2)), (c,List(4, 5)))

【讨论】:

  • 谢谢。我只是在寻找这个。尤其是在形成整数列表的映射时删除字符串部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
相关资源
最近更新 更多