我正在尝试使用 Py03 将列表从 Python 传递给 Rust。我试图将其传递给的函数具有以下签名:
pub fn k_nearest_neighbours(k: usize, x: &[[f32; 2]], y: &[[f32; 3]]) -> Vec<Option<f32>>
我正在为预先存在的库编写绑定,因此我无法更改原始代码。我目前的做事方式是这样的:
// This is example code == DOES NOT WORK
#[pyfunction] // make a new function within a new library with pyfunction macro
fn k_nearest_neighbours(k: usize, x: Vec<Vec<f32>>, y: Vec<f32>) -> Vec<Option<f32>> {
// reformat input where necessary
let x_slice = x.as_slice();
// return original lib's function return
classification::k_nearest_neighbours(k, x_slice, y)
}
该x.as_slice()
函数几乎可以满足我的需要,它给了我一片向量&[Vec<f32>]
,而不是一片片&[[f32; 3]]
。
我希望能够运行这个 Python 代码:
from rust_code import k_nearest_neighbours as knn # this is the Rust function compiled with PyO3
X = [[0.0, 1.0], [2.0, 3.0], [4.0, 5.0], [0.06, 7.0]]
train = [
[0.0, 0.0, 0.0],
[0.5, 0.5, 0.0],
[3.0, 3.0, 1.0],
[4.0, 3.0, 1.0],
]
k = 2
y_true = [0, 1, 1, 1]
y_test = knn(k, X, train)
assert(y_true == y_test)