Sort HashMap data by value
我想按Rust中的值对HashMap数据进行排序(例如,当计算字符串中的字符频率时)。
我想要做的Python等效项是:
1 2 3 4 5 6 7 | 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代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 | // 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吗?我是否可以以某种方式构造
Is this idiomatic Rust?
没有什么特别独特的,除了可能对
1 | let mut count_vec: Vec<_> = count.iter().collect(); |
根据上下文确定
如果您感觉要使用
Can I construct the count_vec in a way so that it would consume the HashMaps data and owns it?
没有任何有意义的方式。仅仅因为
这可能是解决此问题的另一种方式,而无需中间媒介。
1 2 3 4 5 6 7 8 9 | // 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; } let top_char = count.iter().max_by(|a, b| a.1.cmp(&b.1)).unwrap(); println!("Most frequent character in text: {}", top_char.0); |