python 错误 typeerror: list indices must be integers, not str
在本篇文章中,我们的目标是探索如何避免 typeerror: list indices must be integers or slices, not str。
本文讨论以下主题。
- 了解问题的根本原因。
- 复制问题。
- 解决问题。
了解 typeerror: list indices must be integers or slices, not str 的根本原因
typeerror主要发生在python中,每当操作的数据类型出现问题时。 例如,添加两个字符串将导致 typeerror,因为您无法添加两个字符串。
复制 typeerror: list indices must be integers or slices, not str
可以借助以下代码块来复制此问题。
假设我们尝试将某个特定玩家的分数指定为 1,年龄指定为 2,评级指定为 3。 然后我们尝试访问同一玩家的得分。
player = [1,2,3]
print(player["score"])
正如我们从上面的代码块中看到的,我们试图从名为player的数组中找到属性分数。
代码块的输出如下。
typeerror: list indices must be integers or slices, not str
解决python中的错误
为了解决这个问题,我们可以直接使用python中的字典。 可以将前面所示的代码更改为以下内容以消除错误。
player = {'score': 1, 'age': 2, 'rating': 3}
print(player["score"])
代码块的输出如下。
1
因此,在本篇文章的帮助下,我们可以解决python中的这个typeerror。
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
发布时间:2023/07/09 浏览次数:1527 分类:python
-
python错误typeerror: can only concatenate tuple (not "int") to tuple 当您尝试连接除元组之外的任何数据类型的一个或多个值时,会发生此常见错误。
发布时间:2023/07/07 浏览次数:4165 分类:python
-
python 中 typeerror: unhashable type: 'slice' 当我们尝试对给定数据类型执行某些不受支持的操作时,python 中会引发 typeerror。
发布时间:2023/05/31 浏览次数:1045 分类:python
-
本篇文章将讨论 python 中的 typeerror: missing 1 required positional argument: 'self' 错误以及我们如何解决它。让我们讨论引发此错误的情况。不在 python 中实例化对象
发布时间:2023/05/30 浏览次数:653 分类:python
-
本篇文章将讨论python中的 typeerror: can only join an iterable 错误。修复python中 typeerror: can only join an iterable 错误。由于它是 typeerror,我们可以得出结论,正在对给定对象执行不受支持的操作。
发布时间:2023/05/30 浏览次数:276 分类:python
-
我们将在本文中了解为什么会出现 typeerror: 'function' object is not subscriptable,以及我们如何在 python 中修复此错误。
发布时间:2023/05/30 浏览次数:1266 分类:python
-
模 (%) 运算符就是其中一种方法。 它是 python 中最古老的字符串格式化方法之一,以错误的方式使用它可能会导致 typeerror: not all arguments converted during string formatting。
发布时间:2023/05/30 浏览次数:952 分类:python
-
在本文中,我们将讨论为什么 typeerror: nonetype object is not subscriptable 在 python 中出现以及如何修复它。 我们将学习如何对序列数据类型错误地使用 append()、sort() 和 reverse() 等方法导致
发布时间:2023/05/17 浏览次数:250 分类:python
-
本文将讨论 typeerror: unhashable type: 'list' 以及如何在 python 中修复它。因为 python 字典只接受可散列数据类型作为它们的键,而列表是不可散列的。
发布时间:2023/05/17 浏览次数:218 分类:python
-
本文旨在解决当我们尝试打印字符串而不是在函数中使用 return 语句时出现的问题。python 错误typeerror: __str__ returned non-string but printing output