Python自定义myMax函数运行报IndexError: list index out of range如何解决
报错原因
- 代码没有做空输入校验,当调用
myMax([])传入空列表时,maxx=L[0]尝试访问空列表的第0位元素,空列表不存在任何合法索引,因此触发IndexError: list index out of range越界错误。 - 原代码中定义的
f=len(L)变量没有被后续逻辑使用,属于冗余代码可直接删除。
修复方案
可根据业务需求选择以下两种处理方式:
方案1:空列表抛出友好提示(推荐,符合函数预期输入非空的逻辑)
def myMax(L): # 先做非空校验 if not L: raise ValueError("输入列表不能为空,无法求取最大值") ind = 0 maxx = L[0] for i in range(len(L)): if L[i] > maxx: maxx = L[i] ind = i return (ind, maxx) print(myMax([1, 2, -9, 10])) # 输出 (3, 10) # print(myMax([])) # 调用时会抛出明确的ValueError提示,而非模糊的索引越界
方案2:空列表返回约定默认值(适合需要兼容空输入的场景)
def myMax(L): if not L: # 空列表返回提前约定的默认值,可根据业务调整返回规则 return (None, None) ind = 0 maxx = L[0] for i in range(len(L)): if L[i] > maxx: maxx = L[i] ind = i return (ind, maxx) print(myMax([1, 2, -9, 10])) # 输出 (3, 10) print(myMax([])) # 输出 (None, None)
内容的提问来源于stack exchange,提问作者Mandeep Singh
相关产品推荐
相关产品推荐

