解決:python 出現 list assignment index out of range 錯誤


解決:python 出現 list assignment index out of range 錯誤

異常:

Traceback (most recent call last):
File "C:/pythonProject02/new.py", line 12, in
username[i], password[i] = data[i].split('|')
IndexError: list assignment index out of range

代碼:

username = []
password = []
with open('userinfo.txt', 'r', encoding='utf8') as f:
	data = f.readlines()
for i in range(len(data)):
	username[i], password[i] = data[i].split('|')

分析:

list assignment index out of range:列表超過限制

可能就是傳說中的下標越界吧,仔細觀察發現一開始創建username和password變量的時候里面沒有元素,所以當下面 for 循環中 i 不論等於幾,都會出現下標越界,

所以只要使用 .append() 方法,在列表末尾添加單個元素就可以了

username = []
password = []
with open('userinfo.txt', 'r', encoding='utf8') as f:
    data = f.readlines()
for i in range(len(data)):
    username.append(data[i].split('|')[0])
    password.append(data[i].split('|')[1])

一開始只是想着可以使用解壓賦值將兩行合並成一行,沒想到會出現下標越界這種錯誤,還是自己不夠嚴謹。

如有錯漏,歡迎指正和補充


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM