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

如何在PyTorch一维张量中按索引列表选取元素(无循环)

一维PyTorch张量选取指定索引元素的方法

你可以通过两种简洁的方式实现,完全不需要循环:

方法一:直接张量索引

这是最直观的方式,PyTorch支持直接用索引张量对一维张量进行元素选取:

import torch

t = torch.tensor([10., 20., 30., 40., 50., 60.])
indices = torch.tensor([0, 3, 4])
result = t[indices]
print(result)
# 输出: tensor([10., 40., 50.])

方法二:使用torch.index_select

torch.index_select并非只适用于二维张量,一维张量同样可以使用,只需指定维度为0(一维张量唯一的维度):

import torch

t = torch.tensor([10., 20., 30., 40., 50., 60.])
indices = torch.tensor([0, 3, 4])
result = torch.index_select(t, dim=0, index=indices)
print(result)
# 输出: tensor([10., 40., 50.])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:45:41