获得Vec此 Python 代码的 Rust 等效项的最惯用方法是什么?
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]
Run Code Online (Sandbox Code Playgroud)
我可以想出多种不令人满意的方法来做到这一点,但我认为必须有一种使用干净的单行方法iter(),对吧?
let a: Vec<f64> = (0..5).collect::<Vec<i64>>().iter().map(|x| *x as f64).collect();
let a_diff = ???
Run Code Online (Sandbox Code Playgroud)
对于库存 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);
}
Run Code Online (Sandbox Code Playgroud)
(我还将不必要的集合删除到了Vec<i64>.)
当使用 nightly 时,可以缩短为:
#![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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
313 次 |
| 最近记录: |