關于Python?中IndexError:list?assignment?index?out?of?range?錯誤解決
在 Python 中,當您嘗試訪問甚至不存在的列表的索引時,會引發(fā) IndexError: list assignment index out of range。 索引是可迭代對象(如字符串、列表或數組)中值的位置。
在本文中,我們將學習如何修復 Python 中的 Index Error list assignment index out-of-range 錯誤。
Python IndexError:列表分配索引超出范圍
讓我們看一個錯誤的例子來理解和解決它。
代碼示例:
# error program --> IndexError: list assignment index out of range
i = [7,9,8,3,7,0] # index range (0-5)
j = [1,2,3] # index range (0-3)
print(i,"\n",j)
print(f"\nLength of i = {len(i)}\nLength of j = {len(j)}" )
print(f"\nValue at index {1} of list i and j are {i[1]} and {j[1]}")
print(f"\nValue at index {3} of list i and j are {i[3]} and {j[3]}") # error because index 3 isn't available in list j輸出:

上面代碼中 IndexError: list assignment index out of range 背后的原因是我們試圖訪問索引 3 處的值,這在列表 j 中不可用。
修復 Python 中的 IndexError: list assignment index out of range
要修復此錯誤,我們需要調整此案例列表中可迭代對象的索引。 假設我們有兩個列表,你想用列表 b 替換列表 a。
代碼示例:
a = [1,2,3,4,5,6]
b = []
k = 0
for l in a:
b[k] = l # indexError --> because the length of b is 0
k += 1
print(f"{a}\n{a}")輸出:
IndexError: list assignment index out of range
您不能為列表 b 賦值,因為它的長度為 0,并且您試圖在第 k 個索引 b[k] = I 處添加值,因此它會引發(fā)索引錯誤。 您可以使用 append() 和 insert() 修復它。
修復 IndexError: list assignment index out of range 使用 append() 函數
append() 函數在列表末尾添加項目(值、字符串、對象等)。 這很有幫助,因為您不必處理索引問題。
代碼示例:
a = [1,2,3,4,5,6]
b = []
k = 0
for l in a:
# use append to add values at the end of the list
j.append(l)
k += 1
print(f"List a: {a}\nList b: {a}")輸出:
List a: [1, 2, 3, 4, 5, 6]
List b: [1, 2, 3, 4, 5, 6]
修復 IndexError: list assignment index out of range 使用 insert() 函數
insert() 函數可以直接將值插入到列表中的第 k 個位置。 它有兩個參數,insert(index, value)。
代碼示例:
a = [1, 2, 3, 5, 8, 13]
b = []
k = 0
for l in a:
# use insert to replace list a into b
j.insert(k, l)
k += 1
print(f"List a: {a}\nList b: {a}")輸出:
List a: [1, 2, 3, 4, 5, 6]
List b: [1, 2, 3, 4, 5, 6]
除了上述兩種解決方案之外,如果你想像對待其他語言中的普通數組一樣對待 Python 列表,你可以使用 None 值預定義你的列表大小。
代碼示例:
a = [1,2,3,4,5,6]
b = [None] * len(i)
print(f'Length of a: {len(a)}')
print(f'Length of b: {len(b)}')
print(f"\n{a}\n")輸出:
Length of a: 6
Length of b: 6[1, 2, 3, 4, 5, 6]
[None, None, None, None, None, None]
一旦你用虛擬值 None 定義了你的列表,你就可以相應地使用它。
總結
可能有更多的手動技術和邏輯來處理 IndexError:Python 中的列表分配索引超出范圍。 本文概述了兩個常見的列表函數,它們可以幫助我們在替換兩個列表時幫助我們處理 Python 中的索引錯誤。
我們還討論了預定義列表并將其視為類似于其他編程語言數組的數組的替代解決方案。
到此這篇關于Python 中IndexError:list assignment index out of range 錯誤解決的文章就介紹到這了,更多相關Python IndexError錯誤內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python實現將MySQL數據庫表中的數據導出生成csv格式文件的方法
這篇文章主要介紹了Python實現將MySQL數據庫表中的數據導出生成csv格式文件的方法,涉及Python針對mysql數據庫的連接、查詢、csv格式數據文件的生成等相關操作技巧,需要的朋友可以參考下2018-01-01
Python讀取配置文件(config.ini)以及寫入配置文件
這篇文章主要介紹了Python讀取配置文件(config.ini)以及寫入配置文件,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python使用openpyxl設置Excel單元格公式和工作簿合并
這篇文章主要介紹了如何使用Python的openpyxl庫在Excel單元格中設置公式,并展示了如何引用其他工作簿中的單元格內容以及如何合并多個工作簿,需要的朋友可以參考下2025-11-11

