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

Julia技术问题:如何通过另一向量的索引创建新向量

根据指定索引从原向量生成新向量的实现方法

下面针对不同常用工具给出具体实现方案,注意示例中索引是1起始的,部分语言默认0索引需要做转换:

Python 原生列表实现

Python列表默认采用0索引,先将目标索引转换为0起始后,遍历取值即可:

vectorA = [50, 90, 100, 7, 22]
index_tograb = [3, 4, 1]
# 把1起始索引转成0起始
zero_based_indices = [i - 1 for i in index_tograb]
vector_result = [vectorA[i] for i in zero_based_indices]
print(vector_result)  # 输出: [100, 7, 50]

NumPy 数组实现

NumPy支持直接用整数数组做索引,同样需要转换索引起始:

import numpy as np

vectorA = np.array([50, 90, 100, 7, 22])
index_tograb = np.array([3, 4, 1])
vector_result = vectorA[index_tograb - 1]
print(vector_result)  # 输出: [100  7 50]

MATLAB 实现

MATLAB本身默认是1索引,直接用索引向量取值即可:

vectorA = [50, 90, 100, 7, 22];
index_tograb = [3, 4, 1];
vector_result = vectorA(index_tograb);
disp(vector_result);  % 输出: 100  7 50

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 03:22:05