修复 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