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