scala计算字符出现频率
本文介绍了scala计算字符出现频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
现在用了可变dict,觉得写的不好
def times(chars: List[Char]): List[(Char, Int)] = {
import scala.collection.mutable.Map
var res: Map[Char, Int] = Map()
for(char:Char <- chars) {if(res.contains(char)) res.update(char, res(char)+1) else res += (char -> 1)}
res.toList
}
请问应该怎么改进
解决方案
def times(chars: List[Char]): List[(Char, Int)] = chars.groupBy(x=>x).map(y=>(y._1,y._2.length)).toList
看你的意思是判断字符串中的字符出现次数,所以还可以优化为:
def times(s: String): List[(Char, Int)] = s.groupBy(x => x).map(y => (y._1, y._2.length)).toList
这篇关于scala计算字符出现频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文