Scala 如何计算列表中出现的次数 [英] Scala how can I count the number of occurrences in a list
本文介绍了Scala 如何计算列表中出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
val list = List(1,2,4,2,4,7,3,2,4)
我想这样实现:list.count(2)
(返回 3).
I want to implement it like this: list.count(2)
(returns 3).
推荐答案
其他答案的一个更简洁的版本是:
A somewhat cleaner version of one of the other answers is:
val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
s.groupBy(identity).mapValues(_.size)
给出一个Map
,其中包含原始序列中每个项目的计数:
giving a Map
with a count for each item in the original sequence:
Map(banana -> 1, oranges -> 3, apple -> 3)
该问题询问如何查找特定项目的计数.使用这种方法,解决方案需要将所需元素映射到其计数值,如下所示:
The question asks how to find the count of a specific item. With this approach, the solution would require mapping the desired element to its count value as follows:
s.groupBy(identity).mapValues(_.size)("apple")
这篇关于Scala 如何计算列表中出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文