如何将一组值转换为对它们进行计数的 HashMap? [英] How can I convert a collection of values into a HashMap that counts them?
问题描述
我有一个带有重复项的集合,我想创建一个 HashMap
将这些项作为键,以及它们在原始集合中出现的次数.>
我正在处理的具体示例是一个字符串,我想计算每个字符出现的次数.
我可以这样做:
fn into_character_map(word: &str) ->HashMap{让 mut 字符 = HashMap::new();for c in word.chars() {让 entry = characters.entry(c).or_insert(0);*条目 += 1;}人物}
但我想知道是否有更优雅的解决方案.我正在考虑使用 collect()
,但它不维护项目之间的状态,因此似乎不支持我所需要的.
这是在我编写解决Anagram"问题时出现的.>
是否更优雅值得怀疑,但fold
使用 HashMap
需要更少的行:
fn into_character_map(word: &str) ->HashMap{word.chars().fold(HashMap::new(), |mut acc, c| {*acc.entry(c).or_insert(0) += 1;acc})}
I have a collection of items, with repetitions, and I want to create a HashMap
that has the items as keys, and the count of how many times they appear in the original collection.
The specific example I'm working on is a string where I want to count how many times each character appears.
I can do something like this:
fn into_character_map(word: &str) -> HashMap<char, i32> {
let mut characters = HashMap::new();
for c in word.chars() {
let entry = characters.entry(c).or_insert(0);
*entry += 1;
}
characters
}
But I was wondering if there's a more elegant solution. I was thinking of using collect()
, but it doesn't maintain state between items, so doesn't seem to support what I need.
This came up as I was writing my solution to the 'Anagram' problem on Exercism.
It's dubious if it's more elegant, but fold
ing using a HashMap
requires fewer lines:
fn into_character_map(word: &str) -> HashMap<char, i32> {
word.chars().fold(HashMap::new(), |mut acc, c| {
*acc.entry(c).or_insert(0) += 1;
acc
})
}
这篇关于如何将一组值转换为对它们进行计数的 HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!