如何解决此错误:列表索引必须是整数或切片,而不是元组

时间:2019-10-30 16:25:13

标签: python list tensorflow pytorch

假设我有一个名为outputs的张量列表

>> outputs[2][0][0,:,:]
Out[20]: 
tensor([[ 14.0448,  -5.1494,  -0.1780,  ...,  10.1937,  -8.9158,  -5.3964],
        [ 32.0382,  -0.5201,  29.9942,  ..., -18.8268, -23.1068,  23.9745],
        [-24.5911,  14.7233,  -6.3053,  ...,  -5.8131,  -3.3088,   0.5685],
        [  0.8842, -14.8318,   6.7204,  ...,  17.7127,   7.3332,   3.7249],
        [  2.0654, -16.5236,  38.3582,  ..., -23.1663,  -5.1202,  13.6506]],
       grad_fn=<SliceBackward>)


>> outputs[2][1][0,:,:]
Out[24]: 
tensor([[-0.1260,  0.0463, -0.3362,  ...,  0.1089, -0.2454,  0.0140],
        [ 0.5050, -0.0750, -0.1639,  ..., -0.0020, -0.0521, -0.3224],
        [-0.5311,  0.4526,  0.0079,  ..., -0.0654, -0.1255, -0.0012],
        [ 0.0728, -0.1219,  0.0905,  ...,  0.1354,  0.2730, -0.1186],
        [-0.0680, -0.5570,  0.0295,  ..., -0.2411, -0.1690,  0.0331]],
       grad_fn=<SliceBackward>)

当我尝试做时:

>> outputs[2][0:1][0,:,:]

python生成错误,错误消息为

TypeError: list indices must be integers or slices, not tuple

如何解决此错误?

谢谢

2 个答案:

答案 0 :(得分:2)

outputs[2][0]outputs[2][1]都返回一个对象(我想是张量)。
outputs[2][0:1]返回这些对象的列表。
我认为您正在寻找的是outputs[2][0:1][:,0,:,:][a[0,:,:] for a in outputs[2][0:1]]

答案 1 :(得分:2)

在您询问代码示例时,它们就在这里:

import torch

# using small shape to make it printable
outputs_2 = [torch.rand((3,2,1)) for _ in range(2)]

print(outputs_2[0][0,:,:])
# tensor([[0.3294],
#         [0.0031]])

print(outputs_2[1][0,:,:])
# tensor([[0.1910],
#         [0.1547]])

# this is the source of your problem
type(outputs_2[0:1])
# <class 'list'>

我不知道结果如何。这就是我的想法(我将使用[0:2]示例来更清楚):

torch.stack(outputs_2[0:2])[:, 0, :, :]
# tensor([[[0.3294],
#          [0.0031]],
# 
#         [[0.1910],
#          [0.1547]]])

torch.stack(outputs_2[0:2]).shape
# torch.Size([2, 3, 2, 1])