Pytorch Tensor 如何获取元素的索引?

Nic*_*ild 0 python torch pytorch tensor

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

x = torch.tensor(3)
list = torch.tensor([1,2,3,4,5])
Run Code Online (Sandbox Code Playgroud)

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

2
Run Code Online (Sandbox Code Playgroud)

我怎样才能以简单的方式做到这一点?

Was*_*mad 5

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]
Run Code Online (Sandbox Code Playgroud)