You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust ndarray如何从运行时生成的索引中选择数组行?

在Rust ndarray中使用运行时动态索引选择Array2的行

我有一个二维数组Array2,希望能够选择其中的行。通过以下代码可以选择第1、3、6行(对应索引0、2、5):

use ndarray::{Array2, Axis};

let subarray: Array2 = my_array.select(Axis(0), &[0,2,5]);

但当目标索引是在运行时构建的(例如来自Vector或可作为函数输入的可迭代对象),该如何实现行选择呢?

核心解决思路

ndarray的select方法对第二个索引参数的要求是实现NdIndex trait的切片类型,运行时构建的Vec<usize>可以直接通过as_slice()转为符合要求的切片,和编译时的静态数组切片用法完全一致。

具体实现示例

  1. 使用动态构建的Vec<usize>选择行
use ndarray::{Array2, Axis};

fn main() {
    // 初始化示例二维数组
    let my_array = Array2::from_shape_vec((6, 3), (0..18).collect()).unwrap();
    
    // 运行时动态生成索引(模拟从外部输入或计算得到)
    let mut indices = Vec::new();
    indices.push(0);
    indices.push(2);
    indices.push(5);
    
    // 将Vec转为切片传入select
    let subarray: Array2<_> = my_array.select(Axis(0), indices.as_slice());
    println!("{:?}", subarray);
}
  1. 从可迭代对象生成索引后选择行
    如果索引来自可迭代对象(比如Iterator<Item=usize>),只需先将迭代器收集到Vec<usize>中,再转为切片即可:
use ndarray::{Array2, Axis};

fn main() {
    let my_array = Array2::from_shape_vec((6, 3), (0..18).collect()).unwrap();
    
    // 从迭代器收集索引(示例:步长为2的序列)
    let indices: Vec<usize> = (0..6).step_by(2).collect();
    
    let subarray = my_array.select(Axis(0), indices.as_slice());
    println!("{:?}", subarray);
}

关键说明

select方法并不区分编译时静态数组和运行时动态Vec的切片,只要是&[usize]类型(满足NdIndex trait)就能正常工作,这也是ndarray设计中对动态场景的支持。

内容的提问来源于stack exchange,提问作者Andrex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 03:15:06