如何使用来根据值进行boolean_arr过滤?ysbool
这些数组都具有相同的长度。
fn main() {
let xs: Vec<f32> = vec![300., 7.5, 10., 250.];
let boolean_arr: Vec<bool> = xs.into_iter().map(|x| x > 10.).collect();
let ys: Vec<f32> = vec![110.5, 50., 25., 770.];
assert_eq!(wanted_vec, vec![110.5, 770.]);
}
Run Code Online (Sandbox Code Playgroud)
我们可以将zip两者结合起来,然后过滤结果。这是一个适用于任意迭代器的通用函数。
fn filter_by<I1, I2>(bs: I1, ys: I2) -> impl Iterator<Item=<I2 as Iterator>::Item>
where I1: Iterator<Item=bool>,
I2: Iterator {
bs.zip(ys).filter(|x| x.0).map(|x| x.1)
}
Run Code Online (Sandbox Code Playgroud)
以及如何在您的特定用例中调用它
let wanted_vec: Vec<_> = filter_by(boolean_arr.into_iter(), ys.into_iter()).collect();
Run Code Online (Sandbox Code Playgroud)