如何将数组转换为统计各唯一元素出现次数的哈希表?
统计数组元素出现次数生成哈希表
下面是几种主流编程语言的实现方式,核心逻辑都是遍历数组,累加每个元素的出现次数:
Ruby 实现
Ruby 2.7及以上版本自带tally方法,一行搞定:
arr = ["americans", "oath", "oath", "generation", "americans"] count_hash = arr.tally # 输出结果: {"americans"=>2, "oath"=>2, "generation"=>1}
如果用旧版Ruby,手动实现计数:
arr = ["americans", "oath", "oath", "generation", "americans"] count_hash = Hash.new(0) # 初始化哈希表,默认值为0 arr.each { |item| count_hash[item] += 1 } # 结果与上面一致
Python 实现
用标准库的Counter类,简洁高效:
from collections import Counter arr = ["americans", "oath", "oath", "generation", "americans"] count_dict = Counter(arr) # 输出结果: {'americans': 2, 'oath': 2, 'generation': 1}
手动实现的话,用字典的get方法处理初始值:
arr = ["americans", "oath", "oath", "generation", "americans"] count_dict = {} for item in arr: # 元素不存在时默认取0,加1后存回字典 count_dict[item] = count_dict.get(item, 0) + 1
JavaScript 实现
用reduce方法遍历数组并构建计数对象:
const arr = ["americans", "oath", "oath", "generation", "americans"]; const countObj = arr.reduce((acc, curr) => { // 累加计数,不存在的元素初始化为0再加1 acc[curr] = (acc[curr] || 0) + 1; return acc; }, {}); // 输出结果: { americans: 2, oath: 2, generation: 1 }
内容的提问来源于stack exchange,提问作者Bob Kun
相关产品推荐
相关产品推荐

