vec的 rust eclipse 元素间差异

6rqinv9w  于 2023-01-21  发布在  Eclipse
关注(0)|答案(2)|浏览(115)

要获得这段Python代码的Rust vec等价物,最惯用的方法是什么?

import numpy as np
a = np.arange(5)
a_diff = np.diff(a) # this is the thing I'm trying to emulate in Rust
print(a_diff) # [1 1 1 1]

我可以找出许多不令人满意的方法来完成这一任务,但我认为必须有一个使用iter()的干净的一行程序方法,对吗?

let a: Vec<f64> = (0..5).collect::<Vec<i64>>().iter().map(|x| *x as f64).collect();
let a_diff = ???
wztqucjr

wztqucjr1#

如果您正在处理Vec,则可以使用windows

let a: Vec<f64> = (0..5).map(|x| x as f64).collect();
let a_diff: Vec<f64> = a.windows(2).map(|s| s[1] - s[0]).collect();

如果只想使用迭代器,可以使用scan,但它更复杂:

let mut a = (0..5).map(|x| x as f64);
let a_diff: Vec<f64> = if let Some(first) = a.next() {
    a.scan(first, |prev, x| {
        let out = x - *prev;
        *prev = x;
        Some(out)
    }).collect()
} else { vec![] };

或者您可以使用itertools机箱中的tuple_windows

use itertools::Itertools;

let a = (0..5).map(|x| x as f64);
let a_diff: Vec<f64> = a.tuple_windows().map(|(a, b)| b - a).collect();
iklwldmw

iklwldmw2#

对于库存Rust,我会使用windows

fn main() {
    let a: Vec<f64> = (0..5).map(|x| x as f64).collect();
    let a_diff: Vec<f64> = a
        .windows(2)
        .map(|vs| {
            let [x, y] = vs else { unreachable!() };
            y - x
        })
        .collect();
    dbg!(a_diff);
}

(我还将不必要的集合移到了Vec<i64>中。)
当夜间使用时,可以缩短为:

#![feature(array_windows)]
fn main() {
    let a: Vec<f64> = (0..5).map(|x| x as f64).collect();
    let a_diff: Vec<f64> = a.array_windows().map(|[x, y]| y - x).collect();
    dbg!(a_diff);
}

相关问题