Tôi muốn sắp xếp dữ liệu HashMap theo giá trị trong Rust (ví dụ: khi tính tần suất ký tự trong một chuỗi).Sắp xếp dữ liệu HashMap theo giá trị
Các Python tương đương với những gì tôi đang cố gắng làm là:
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])
đang Rust tương ứng của tôi trông như thế này:
// 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);
là Rust thành ngữ này? Tôi có thể xây dựng count_vec
theo cách sao cho nó sẽ tiêu thụ dữ liệu HashMaps và sở hữu nó (ví dụ: sử dụng map()
)? Điều này có phải là idomatic hơn?