我想按Rust中的值对HashMap数据进行排序(例如,在计算字符串中的字符频率时).
与我try 做的工作类似的Python是:
count = {}
for c in text:
count[c] = count.get('c', 0) + 1
sorted_data = sorted(count.items(), key=lambda item: -item[1])
print('Most frequent character in text:', sorted_data[0][0])
我对应的防 rust 代码如下所示:
// Count the frequency of each letter
let mut count: HashMap<char, u32> = HashMap::new();
for c in text.to_lowercase().chars() {
*count.entry(c).or_insert(0) += 1;
}
// Get a sorted (by field 0 ("count") in reversed order) list of the
// most frequently used characters:
let mut count_vec: Vec<(&char, &u32)> = count.iter().collect();
count_vec.sort_by(|a, b| b.1.cmp(a.1));
println!("Most frequent character in text: {}", count_vec[0].0);
这是惯用的 rust 吗?我能否以某种方式构造count_vec
,使其能够使用HashMaps数据并拥有它(例如,使用map()
)?这会不会更像我的风格?