HashMapデータを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])
マイ対応錆コードは次のようになります。
// 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);
は、この慣用的な錆ですか? count_vec
を、HashMapsデータを消費して所有するように構築することはできますか(たとえば、map()
を使用)。これはより愚かではないか?