我能够将我的输入有效地解析为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?
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)
也可以看看:
| 归档时间: |
|
| 查看次数: |
1043 次 |
| 最近记录: |