Python報錯及解決:IndexError: list index out of range
報錯解釋
該報錯是由于超出list范圍導(dǎo)致文章來源地址http://www.zghlxwxcb.cn/news/detail-565966.html
解決方式
- 索引前先查詢list范圍, 或用if idx in range(len(test_list))判斷索引是否在列表list的范圍內(nèi):
if idx in range(len(test_list)):
print(test_list[idx])
else:
print(f"{idx} exceed list range:{test_list}") # 超出list范圍
- 多個判斷條件是先定義好邊界情況再進入其他情況
- 下圖 if 的4個循環(huán)中,如果先進行正常判斷,再討論邊界,則在前兩個if循環(huán)中就可能出現(xiàn)IndexError: list index out of range報錯,此時調(diào)整 if 順序,先定義好邊界就能解決該報錯
while a >= 0 or b < n: #只要滿足其中一個條件,就可以接著填數(shù);不滿足某個條件是因為該組以達到邊界
if a < 0: #負數(shù)組已達到邊界,后續(xù)就是正數(shù)組往后加
ans.append(nums[b]*nums[b])
b += 1
elif b >= n: #正數(shù)組已達到邊界,后續(xù)就是負數(shù)組往后加
ans.append(nums[a]*nums[a])
a -= 1
#需要先把邊界情況定義好,否則可能會出現(xiàn)IndexError: list index out of range的報錯
elif nums[a]*nums[a] <= nums[b]*nums[b]: #則先將a放入新數(shù)組
ans.append(nums[a]*nums[a])
a -= 1
elif nums[a]*nums[a] > nums[b]*nums[b]: #則先將b放入新數(shù)組
ans.append(nums[b]*nums[b])
b += 1
return ans
文章來源:http://www.zghlxwxcb.cn/news/detail-565966.html
到了這里,關(guān)于Python報錯及解決:IndexError: list index out of range的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!