【问题标题】:How Pytorch Tensor get the index of elements? [duplicate]Pytorch Tensor 如何获取元素的索引? [复制]
【发布时间】:2020-01-15 22:18:11
【问题描述】:

我有 2 个名为 xlist 的张量,它们的定义如下:

x = torch.tensor(3)
list = torch.tensor([1,2,3,4,5])

现在我想从 list 中获取元素 x 的索引。预期的输出是一个整数:

2

我怎样才能轻松完成?

【问题讨论】:

标签: python pytorch torch tensor


【解决方案1】:
import torch

x = torch.tensor(3)

list = torch.tensor([1,2,3,4,5])
idx = (list == x).nonzero().flatten()
print (idx.tolist()) # [2]

list = torch.tensor([1,2,3,3,5])
idx = (list == x).nonzero().flatten()
print (idx.tolist()) # [2, 3]

【讨论】:

    猜你喜欢
    • 2018-05-31
    • 1970-01-01
    • 2019-09-22
    • 2012-11-21
    • 1970-01-01
    • 2020-03-16
    • 2021-01-25
    • 1970-01-01
    • 2020-06-10
    相关资源
    最近更新 更多