Why does code A runs well whereas B got an error?
I encountered a question when I try to understand a line of code:
scores = [s[tuple(k.t())] for s, k in zip(scores, keypoints)].
Here I am going to give the code that can reproduce it:
import torch # v1.5.1

scores = [torch.rand(480, 640)]
keypoints = [torch.randint(0, 480, [978, 2])]

scores = [s[tuple(k.t())] for s, k in zip(scores, keypoints)] # label A, OK

for s, k in zip(scores, keypoints):
    print(s[tuple(k.t())]) # label B, Error

&gt;&gt;&gt; IndexError: too many indices for tensor of dimension 1


I think the above two kinds of code (A and B respectively) are almost the same, but the latter threw out an error. I discussed it with my roommate but we have no idea what's going on.
Could someone help me? Thanks in advance!

You can just change the order of A and B, for you have already changed &quot;scores&quot; when you execute B. It will definitely works.
import torch
scores = [torch.rand(2, 3)]
keypoints = [torch.randint(0, 2, [4, 2])]

for s, k in zip(scores, keypoints):
    print(s[tuple(k.t())]) # label B, Error (now ok)

scores = [s[tuple(k.t())] for s, k in zip(scores, keypoints)] # label A, OK
print(scores)

The output is
[tensor([0.3175, 0.6934, 0.2842, 0.3175])]
[tensor([0.3175, 0.6934, 0.2842, 0.3175])]

which is exactly the same.
