将长度为2的迭代器收集到HashMap中

tur*_*too 5 rust

我能够将我的输入有效地解析为Iterator<Iterator<i32>>每个内部迭代器的长度为2的地方。输入看起来像:

0: 3
1: 2
2: 4
4: 8
6: 5
8: 6
...
Run Code Online (Sandbox Code Playgroud)

我可以解析为:

input.lines()
     .map(|line| line.split(": ")
                     .filter_map(|n| n.parse::<i32>().ok()))
Run Code Online (Sandbox Code Playgroud)

我想到的最好的方法HashMap是:

let mut tmp_map: HashMap<i32, i32> = HashMap::new();
for mut pair in input.lines()
                     .map(|line| line.split(": ")
                                     .filter_map(|n| n.parse::<i32>().ok()))
{
    tmp_map.insert(pair.next().unwrap(), pair.next().unwrap());
}
Run Code Online (Sandbox Code Playgroud)

...这似乎很笨拙。有没有办法将此迭代器收集到中HashMap?

操场

She*_*ter 6

HashMap实施FromIterator<(K, V)>。然后,只需将文本转换为元组的迭代器即可。我喜欢使用Itertools::tuples:

const INPUT: &str = r#"0: 3
1: 2
2: 4
4: 8
6: 5
8: 6"#;

extern crate itertools;

use std::collections::HashMap;
use itertools::Itertools;

fn main() {
    let z: HashMap<u8, u8> = INPUT
        .lines()
        .flat_map(|l| l.split(":"))
        .flat_map(|n| n.trim().parse())
        .tuples()
        .collect();

    println!("{:?}", z);
}
Run Code Online (Sandbox Code Playgroud)

也可以看看:

  • 就像一个注释:我认为这会产生一连串的数字,然后成对选择它们。也就是说,不管输入是“ 1:2 \ n3:4 \ n”,“ 1 \ n2 \ n3 \ n4 \ n”还是“ 1:2:3:4”(它也会忽略所有解析错误) afaict)。 (2认同)