MST

星途 面试题库

面试题:Python列表嵌套索引错误分析

有一个嵌套列表`nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]`,编写代码实现一个函数,该函数接收一个索引元组,例如`(1, 2)`代表访问`nested_list[1][2]`,但要考虑到可能发生的各种列表索引错误情况,如外层索引越界、内层索引越界等,对错误进行捕获并合理提示错误信息。说明你处理不同错误的思路。
35.4万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def access_nested_list(nested_list, index_tuple):
    try:
        if len(index_tuple) != 2:
            raise ValueError("索引元组长度必须为2")
        outer_index, inner_index = index_tuple
        if outer_index < 0 or outer_index >= len(nested_list):
            raise IndexError("外层索引越界")
        sub_list = nested_list[outer_index]
        if inner_index < 0 or inner_index >= len(sub_list):
            raise IndexError("内层索引越界")
        return sub_list[inner_index]
    except ValueError as ve:
        print(f"值错误: {ve}")
    except IndexError as ie:
        print(f"索引错误: {ie}")


nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
index = (1, 2)
result = access_nested_list(nested_list, index)
if result is not None:
    print(result)

处理不同错误的思路

  1. 值错误处理:检查索引元组的长度是否为2,如果不是,抛出ValueError并给出相应提示,因为题目要求索引元组长度固定为2。
  2. 外层索引越界处理:判断外层索引是否在合法范围内(大于等于0且小于嵌套列表的长度),如果不在,抛出IndexError并提示外层索引越界。
  3. 内层索引越界处理:获取对应外层索引的子列表后,判断内层索引是否在子列表的合法范围内,若不在,抛出IndexError并提示内层索引越界。通过try - except块捕获异常并给出合理的错误提示信息。