按 Rust 中的值对哈希图进行排序

use*_*713 0 rust

在python中它是这样完成的:

>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}

{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Run Code Online (Sandbox Code Playgroud)

如何通过rust中的值来缩短hashmap?

到目前为止我的代码:

use std::collections::HashMap;

fn main() {
    let mut count: HashMap<String, u32>= HashMap::new();
    count.insert(String::from("A"), 5);
    count.insert(String::from("B"), 2);
    count.insert(String::from("C"), 11);
    count.insert(String::from("D"), 10);

    let highest = count.iter().max_by(|a, b| a.1.cmp(&b.1)).unwrap();

    println!("largest hash: {:?}", highest); // largest hash: ("C", 11)
}
Run Code Online (Sandbox Code Playgroud)

use*_*713 11

是的,通过转换为向量对其进行排序:

use std::collections::HashMap;

fn main() {
    let mut count: HashMap<String, u32>= HashMap::new();
    count.insert(String::from("A"), 5);
    count.insert(String::from("B"), 2);
    count.insert(String::from("C"), 11);
    count.insert(String::from("D"), 10);

    let mut hash_vec: Vec<(&String, &u32)> = count.iter().collect();
    println!("{:?}", hash_vec);
    hash_vec.sort_by(|a, b| b.1.cmp(a.1));

    println!("Sorted: {:?}", hash_vec); //Sorted: [("C", 11), ("D", 10), ("A", 5), ("B", 2)]
}
Run Code Online (Sandbox Code Playgroud)

按值对 HashMap 数据进行排序


Mas*_*inn 6

与 Python 的 不同dict,Rust 的“内置”hashmap 没有排序,因此排序没有任何影响。

如果出于某种原因需要有序映射,则应使用indexmap。另外,BTreeMap分类基础上的关键。

由于您并没有真正提出任何令人信服的用例,因此很难提供建议。