[英]Why am I getting this “list index out of range” error?
def numline(name)
返回文本文件的行數
def anyLine(name,n)
返回文本文件的任何一行,每一行(在我的文本文件上)都有三個制表符('\t')
如果我在沒有循環的情況下運行程序,我會得到我想要的答案,但是當我使用 for 循環時,我會不斷收到錯誤
(dictConcepts[a_string[0], a_string[2].rstrip('\n')] = a_string[1]
IndexError:列表索引超出范圍)
這是我的代碼:
def main(name):
for i in range(0, numLine(name)):
a_string = anyLine(name, i).split('\t')
dictConcepts[a_string[0], a_string[2].rstrip('\n')] = a_string[1]
for key in dictConcepts:
print(key, ':', dictConcepts[key])
現在,如果:
a_string = anyLine(name, i).split('\t')
不會產生至少長度為三的列表,(即\t
在該行中出現兩次)您的代碼將因索引錯誤而失敗。
你可以編寫一個try
/ except
,這樣你就不會索引不存在的東西:
a_string = anyLine(name, i).split('\t')
try:
dictConcepts[a_string[0], a_string[2].rstrip('\n')] = a_string[1]
except IndexError:
print('something is not right here')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.