[英]List of lists TypeError: list indices must be integers or slices, not tuple
Here is my list of lists and I'm trying to print a certain element:这是我的列表列表,我正在尝试打印某个元素:
boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[..., 0:1])
I get a我得到一个
TypeError: list indices must be integers or slices, not tuple
Your syntax is incorrect, use following syntax to get the elements inside list: list_name[index_of_outer_list_item][index_of_inner_list_item]
so by that if you want let's say 300 of 1st list inside the outer list:您的语法不正确,请使用以下语法获取列表中的元素:
list_name[index_of_outer_list_item][index_of_inner_list_item]
因此,如果您想假设外部列表中的第一个列表中的 300 个:
boxes_preds[0][1]
this should do it.这应该这样做。
You can imagine the index as 2D coordinates written in form [y][x]
.您可以将索引想象为以
[y][x]
形式编写的 2D 坐标。 Like when the nested lists represent a 2D matrix:就像嵌套列表表示 2D 矩阵一样:
y / x
| 1, 300, 400, 250, 350
| 0, 450, 150, 500, 420
Where x
and y
both must be integers or in slice-notation:其中
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]
There is a way to use tuples to index.有一种方法可以使用元组进行索引。 As data-structure to store a 2D-index, but not as tuple inside the brackets:
作为存储二维索引的数据结构,但不作为括号内的元组:
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
See Python - using tuples as list indices .请参阅Python - 使用元组作为列表索引。
...
...
The ellipsis (three dots) is a special syntax element used in Numpy or as output representation in Python.省略号(三个点)是Numpy中使用的特殊语法元素或 Python 中的输出表示。
However it is not allowed as list-index.但是,它不允许作为列表索引。 Following example demonstrates the error:
以下示例演示了错误:
boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[...])
Output:输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not ellipsis
See:看:
You have to do this:你必须这样做:
boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[0][0:1])
boxes_preds[0]
returns the first list in the boxes_preds
, and then you use your slicing / index to access the elements of that list. boxes_preds[0]
返回boxes_preds
中的第一个列表,然后您使用切片/索引访问该列表的元素。
You would do the same to access later elements of boxes_preds
, such as boxes_preds[1]
to access the second list.您可以执行相同的操作来访问
boxes_preds
的后续元素,例如boxes_preds[1]
以访问第二个列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.