[英]List of lists TypeError: list indices must be integers or slices, not tuple
这是我的列表列表,我正在尝试打印某个元素:
boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[..., 0:1])
我得到一个
TypeError: list indices must be integers or slices, not tuple
您的语法不正确,请使用以下语法获取列表中的元素: list_name[index_of_outer_list_item][index_of_inner_list_item]
因此,如果您想假设外部列表中的第一个列表中的 300 个:
boxes_preds[0][1]
这应该这样做。
您可以将索引想象为以[y][x]
形式编写的 2D 坐标。 就像嵌套列表表示 2D 矩阵一样:
y / x
| 1, 300, 400, 250, 350
| 0, 450, 150, 500, 420
其中x
和y
都必须是整数或切片符号:
boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[0][0]) # integer index for both
# 1
print(boxes_preds[-1][0:2]) # last of outer list, slice index for inner
# [0, 450]
有一种方法可以使用元组进行索引。 作为存储二维索引的数据结构,但不作为括号内的元组:
coordinates_tuple = (1,1) # define the tuple of coordinates (y,x)
y,x = coordinates_tuple # unpack the tuple to distinct variables
print(boxes_preds[y][x]) # use those in separate indices
# 450
...
省略号(三个点)是Numpy中使用的特殊语法元素或 Python 中的输出表示。
但是,它不允许作为列表索引。 以下示例演示了错误:
boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[...])
输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not ellipsis
看:
你必须这样做:
boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[0][0:1])
boxes_preds[0]
返回boxes_preds
中的第一个列表,然后您使用切片/索引访问该列表的元素。
您可以执行相同的操作来访问boxes_preds
的后续元素,例如boxes_preds[1]
以访问第二个列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.