[英]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.