迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

修复 Python 中 TypeError: List Indices Must Be Integers, Not List 错误

作者:迹忆客 最近更新:2023/05/11 浏览次数:

我们将介绍嵌套列表以及许多程序员在尝试通过 Python 中的示例访问其中的元素时遇到的常见错误。


修复 TypeError: list indices must be integers, not list in Python

列表是 Python 最常用和最通用的数据类型之一。 列表可用于各种应用程序。

嵌套列表包含在其中包含列表的元素。 它也被称为嵌套数组,用于存储、组织和操作多维数据。

下面显示了 Python 中嵌套列表的示例。

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

这是使用嵌套列表时的常见错误。 访问嵌套列表中的项目时,我们需要指定其索引两次。

第一个用于外部列表,第二个用于内部列表。

让我们尝试使用 Python 从上面的示例中访问 5,如下所示。

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
find_five = nested_list[1][1]
print(find_five)

上面代码的输出将如下所示。

list indices 必须是整数,而不是 list in Python first example

但是如果我们尝试错误地访问一个元素,我们就会得到错误信息。 让我们尝试重新创建可能发生此错误的情况。

例如,如果我们尝试传递一个具有两个值的索引,而不是分别传递两个索引,则会抛出错误。

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
find_five = nested_list[1,1]
print(find_five)

这将引发如下所示的错误。

list indices must be integer, not list in Python 错误第一个例子

还有一种情况,当我们将变量中的索引错误地保存为列表而不是类型 int 时,我们可能会遇到相同的错误,如下所示。

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
indice_one = [1]
indice_two = [2]
find_six = nested_list[indice_one][indice_two]
print(find_six)

上面代码的输出如下所示。

list indices must be integer, not list in Python 错误第二个例子

避免此错误的最佳方法是通过正确类型的索引调用项目。 如果将索引存储在变量中,则需要将它们分配为整数,如下所示。

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
indice_one = 1
indice_two = 2
find_six = nested_list[indice_one][indice_two]
print(find_six)

将索引的值分配为 int 类型永远不会引发错误。 上面的代码将运行如下所示。

list indices must be integer, not list in Python报错优先解决办法

总之,嵌套列表是 Python 中一种强大的数据结构,但重要的是要记住列表只能使用整数进行索引。 如果我们遇到 TypeError: list indices must be integers, not list 错误,我们正在尝试使用不是整数的值访问列表。

要解决此错误,请改用整数值。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便