IndexError:元组索引在 Python 中超出范围 [已解决]

IndexError: 元组索引在 Python 中超出范围

IndexError: tuple index out of range in Python

当我们尝试访问元组中不存在的索引时,会出现 Python“IndexError: tuple index out of range”。

Python 中的索引是从零开始的,因此元组中第一项的索引是0,最后一项的索引是-1or len(my_tuple) - 1

indexerror 元组索引超出范围

下面是错误如何发生的示例。

主程序
my_tuple = ('a', 'b', 'c') # ⛔️ IndexError: tuple index out of range print(my_tuple[3])

元组的长度为3由于 Python 中的索引是从零开始的,因此元组中的第一项的索引为0,最后一项的索引为2

A b C
0 1个 2个
如果我们尝试访问 范围之外的任何正索引0-2,我们将得到一个IndexError.

获取元组的最后一项

如果您需要获取元组中的最后一项,请使用-1.

主程序
my_tuple = ('a', 'b', 'c') print(my_tuple[-1]) # 👉️ c print(my_tuple[-2]) # 👉️ b

当索引以负号开头时,我们从元组的末尾开始倒数。

获取元组的长度

如果需要获取元组的长度,请使用该len()函数。

主程序
my_tuple = ('a', 'b', 'c') print(len(my_tuple)) # 👉️ 3 idx = 3 if len(my_tuple) > idx: print(my_tuple[idx]) else: # 👇️ this runs print(f'index {idx} is out of range')

len ()函数返回对象的长度(项目数)。

该函数采用的参数可以是序列(字符串、元组、列表、范围或字节)或集合(字典、集合或冻结集合)。

如果一个元组的长度为3,那么它的最后一个索引是(因为索引是从零开始的)。 2

这意味着您可以检查元组的长度是否大于您尝试访问的索引。

使用 range() 遍历一个元组

如果您尝试使用该函数遍历元组range(),请使用元组的长度。

主程序
my_tuple = ('a', 'b', 'c') for i in range(len(my_tuple)): print(i, my_tuple[i]) # 👉️ 0 a, 1 b, 2 c

但是,更好的解决方案是使用该enumerate()函数迭代具有索引的元组。

主程序
my_tuple = ('a', 'b', 'c') for index, item in enumerate(my_tuple): print(index, item) # 👉️ 0 a, 1 b, 2 c

enumerate函数接受一个可迭代对象并返回一个包含元组的枚举对象,其中第一个元素是索引,第二个
项目。

使用try/except语句来处理错误

处理“IndexError:元组索引超出范围”异常的另一种方法是使用块try/except

主程序
my_tuple = ('a', 'b', 'c') try: result = my_tuple[100] except IndexError: print('index out of range')

100我们尝试访问引发异常的索引处的元组项IndexError

您可以处理错误或使用块pass中的关键字except

尝试访问任何索引处的空元组会导致错误

请注意,如果您尝试访问特定索引处的空元组,您总是会得到一个IndexError.

主程序
my_tuple = () print(my_tuple) # 👉️ () print(len(my_tuple)) # 👉️ 0 # ⛔️ IndexError: tuple index out of range print(my_tuple[0])

您应该打印您尝试访问的元组及其长度,以确保变量存储您期望的内容。

元组与列表非常相似,但实现的内置方法较少并且是不可变的(无法更改)。

万一你错误地声明了一个元组,元组有多种构造方式:

  • 使用一对括号()创建一个空元组
  • 使用尾随逗号 –a,(a,)
  • Separating items with commas – a, b or (a, b)
  • Using the tuple() constructor

The error isn’t raised when using tuple slicing #

Note that the error isn’t raised when using tuple slicing.

The syntax for tuple slicing is my_tuple[start:stop:step].

The start index is inclusive and the stop index is exclusive (up to, but not
including).

If the start index is omitted, it is considered to be 0, if the stop index
is omitted, the slice goes to the end of the tuple.

main.py
my_tuple = ('a', 'b', 'c', 'd') print(my_tuple[0:2]) # 👉️ ('a', 'b') print(my_tuple[2:100]) # 👉️ ('c', 'd') print(my_tuple[2:]) # 👉️ ('c', 'd') print(my_tuple[:2]) # 👉️ ('a', 'b')

Python indexes are zero-based, so the first item in a tuple has an index of 0,
and the last item has an index of -1 or len(my_tuple) - 1.

Conclusion #

当我们尝试访问元组中不存在的索引时,会出现 Python“IndexError: tuple index out of range”。

Python 中的索引是从零开始的,因此元组中第一项的索引是0,最后一项的索引是-1or len(my_tuple) - 1