简体   繁体   English

Scala-如何按出现来对元素进行分组?

[英]Scala - How to group elements by occurrence?

Is there a function in scala that groups all elements of a list by the number of these occurrences? Scala中是否有一个功能可以按出现次数将列表的所有元素分组?

For example, I have this list: 例如,我有以下列表:

val x = List("c", "b", "b", "c", "a", "d", "c")

And I want to get a new list like that: 我想得到一个像这样的新清单:

x = List((3, "c"), (2, "b"), (1, "a"), (1, "d"))

You can first count the occurrences of each element and then reverse the resulting tuples: 您可以先计算每个元素的出现次数 ,然后反转结果元组:

List("c", "b", "b", "c", "a", "d", "c")
  .groupBy(identity).mapValues(_.size) // Map(b -> 2, d -> 1, a -> 1, c -> 3)
  .toList                              // List((b,2), (d,1), (a,1), (c,3))
  .map{ case (k, v) => (v, k) }        // List((2,b), (1,d), (1,a), (3,c))

You don't specifically mention a notion of order for the output, but if this was a requirement, this solution would need to be adapted. 您没有特别提到输出顺序的概念,但是如果这是必需的,则需要对这种解决方案进行调整。

Try this to get exactly what you want in the order you mentioned. 尝试执行此操作以按照您提到的顺序确切获得所需的内容。 (ie., order preserved in the List while taking counts): (即, 计数时保留在列表中的订单 ):

x.distinct.map(v=>(x.filter(_==v).size,v))

In SCALA REPL: 在SCALA REPL中:

scala> val x = List("c", "b", "b", "c", "a", "d", "c")
x: List[String] = List(c, b, b, c, a, d, c)

scala> x.distinct.map(v=>(x.filter(_==v).size,v))
res225: List[(Int, String)] = List((3,c), (2,b), (1,a), (1,d))

scala>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM