rust 如何得到向量的相邻差?

fsi0uk1n  于 2023-10-20  发布在  其他
关注(0)|答案(2)|浏览(131)

获取此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 = ???
brjng4g3

brjng4g31#

对于股票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);
}
tzdcorbm

tzdcorbm2#

如果你正在处理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 crate中使用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();

相关问题