迭代两个向量和其他向量

use*_*932 3 rust

由于输入我有两个Vec Iterator::zip,并xs作为输出我要打印

c1 X,c2 Y.

休息c1 X < - 如果a.len()> b.len()

休息c2 Y < - 如果a.len()<b.len()

一种可能的解决方案是

let xs = vec![1, 2, 3, 4, 5];
let ys = vec![11, 12, 13];
Run Code Online (Sandbox Code Playgroud)

但是对于其他的我需要复杂的代码来检查长度并完成其余部分.

所以我写道:

x=1, y=11
x=2, y=12
x=3, y=13
x=4; no matching Y
x=5; no matching Y
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为ys在这种情况下我有额外的电话:

for (x, y) in xs.iter().zip(ys.iter()) {
    println!("x={}, y={}", x, y);
}
Run Code Online (Sandbox Code Playgroud)

是否有可能在迭代器的帮助下解决而不切割其他更大的Vec

mca*_*ton 8

itertools有一个方法zip_longest可以做到这一点:

use itertools::Itertools;
use itertools::EitherOrBoth::{Both, Left, Right};

for it in xs.iter().zip_longest(ys.iter()) {
    match it {
        Both(x, y) => println!("x={}, y={}", x, y),
        Left(x) => println!("x={}, no matching Y", x),
        Right(y) => println!("y={}, no matching X", y),
    }
}
Run Code Online (Sandbox Code Playgroud)


aSp*_*pex 6

没有外部包装箱的实施:

let mut it_xs = xs.iter();
let mut it_ys = ys.iter();
loop {
    match (it_xs.next(), it_ys.next()) {
        (Some(x), Some(y)) => println!("x={}, y={}", x, y),
        (Some(x), None) => println!("x={}, no matching Y", x),  
        (None, Some(y)) => println!("y={}, no matching X", y), 
        (None, None) => break,
    }
}
Run Code Online (Sandbox Code Playgroud)