【发布时间】:2016-01-01 11:45:56
【问题描述】:
我想在 Rust 中按值对 HashMap 数据进行排序(例如,在计算字符串中的字符频率时)。
我正在尝试做的 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())?这会更符合规范吗?
【问题讨论】:
-
我猜你的意思是“按字段 1”? (在您的评论中)
标签: rust