修復 Python 中的物件不可下標錯誤

Haider Ali 2022年5月17日
修復 Python 中的物件不可下標錯誤

在 Python 中,object is not subscriptable 錯誤是不言自明的。如果你在 Python 中遇到此錯誤並正在尋找解決方案,請繼續閱讀。

修復 Python 中的 object is not subscriptable 錯誤

首先,我們需要了解這個錯誤的含義,我們必須知道 subscriptable 是什麼意思。

下標是程式語言中用於標識元素的符號或數字。所以,通過 object is not subscriptable,很明顯資料結構沒有這個功能。

例如,看看下面的程式碼。

# An integer
Number = 123

Number[1]  # trying to get its element on its first subscript

執行上面的程式碼將導致錯誤,因為整數沒有多個值。因此,需要整數下標是沒有意義的。讓我們再看一些例子。

# Set always has unique Elements
Set = {1, 2, 3}

# getting second index of set #wrong
Set[2]

我們用一些值初始化了一個集合;不要將其誤認為是列表或陣列。集合沒有下標。意思是,上面的程式碼也會給出同樣的錯誤。

我們不能顯示集合中的單個值。如果我們使用迴圈列印設定值,你會注意到它不遵循任何順序。

沒有確定其價值的指標。以下程式碼的輸出將給出不同的順序輸出。

# Set always has unique Elements
Set = {1, 2, 4, 5, 38, 9, 88, 6, 10, 13, 12, 15, 11}

# getting second index of set
for i in Set:
    print(i)

當涉及到字串或列表時,你可以使用下標來標識每個元素。這就像列印並從一個簡單的陣列中獲取一個值。看一看。

# string variable
string = "Hello I am Python"

print(string[4])

輸出:

o

上面的程式碼將成功執行,輸出將是 o,因為它出現在字串的第五個索引/下標 (0-4) 上。該物件是可下標的。

# function which returns a list
def my_Func():
    return list(range(0, 10))


# correct
print(my_Func()[3])

輸出:

3

在上面的程式碼中,我們有一個函式返回一個可下標的列表。如你所見,我們正在顯示列表的第三個元素並使用下標和索引方法。

作者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

相關文章 - Python Error

相關文章 - Python Object