在 Python 中,當(dāng)您嘗試訪問甚至不存在的列表的索引時(shí),會(huì)引發(fā) IndexError: list assignment index out of range。 索引是可迭代對(duì)象(如字符串、列表或數(shù)組)中值的位置。
在本文中,我們將學(xué)習(xí)如何修復(fù) Python 中的 Index Error list assignment index out-of-range 錯(cuò)誤。
Python IndexError:列表分配索引超出范圍
讓我們看一個(gè)錯(cuò)誤的例子來理解和解決它。
代碼示例:
# 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 背后的原因是我們?cè)噲D訪問索引 3 處的值,這在列表 j 中不可用。
修復(fù) Python 中的 IndexError: list assignment index out of range
要修復(fù)此錯(cuò)誤,我們需要調(diào)整此案例列表中可迭代對(duì)象的索引。 假設(shè)我們有兩個(gè)列表,你想用列表 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 賦值,因?yàn)樗拈L(zhǎng)度為 0,并且您試圖在第 k 個(gè)索引 b[k] = I 處添加值,因此它會(huì)引發(fā)索引錯(cuò)誤。 您可以使用 append()
和 insert()
修復(fù)它。
修復(fù) IndexError: list assignment index out of range 使用 append() 函數(shù)
append() 函數(shù)在列表末尾添加項(xiàng)目(值、字符串、對(duì)象等)。 這很有幫助,因?yàn)槟槐靥幚硭饕龁栴}。
代碼示例:
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]
修復(fù) IndexError: list assignment index out of range 使用 insert() 函數(shù)
insert()
函數(shù)可以直接將值插入到列表中的第 k 個(gè)位置。 它有兩個(gè)參數(shù),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]
除了上述兩種解決方案之外,如果你想像對(duì)待其他語言中的普通數(shù)組一樣對(duì)待 Python 列表,你可以使用 None 值預(yù)定義你的列表大小。
代碼示例:
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{b}")
輸出:
Length of a: 6
Length of b: 6
[1, 2, 3, 4, 5, 6]
[None, None, None, None, None, None]
一旦你用虛擬值 None 定義了你的列表,你就可以相應(yīng)地使用它。
總結(jié)
可能有更多的手動(dòng)技術(shù)和邏輯來處理 IndexError:Python 中的列表分配索引超出范圍。 本文概述了兩個(gè)常見的列表函數(shù),它們可以幫助我們?cè)谔鎿Q兩個(gè)列表時(shí)幫助我們處理 Python 中的索引錯(cuò)誤。文章來源:http://www.zghlxwxcb.cn/news/detail-735017.html
我們還討論了預(yù)定義列表并將其視為類似于其他編程語言數(shù)組的數(shù)組的替代解決方案。文章來源地址http://www.zghlxwxcb.cn/news/detail-735017.html
到了這里,關(guān)于Python 中IndexError: list assignment index out of range 錯(cuò)誤解決的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!