简体   繁体   English

为什么我会收到此“列表索引超出范围”错误?

[英]Why am I getting this “list index out of range” error?

def numline(name) returns a number of lines in of a text file def numline(name)返回文本文件的行数

def anyLine(name,n) returns any line of a text file and each line (on my text file) have three tabs ('\t') def anyLine(name,n)返回文本文件的任何一行,每一行(在我的文本文件上)都有三个制表符('\t')

If I run the program without the loop, I get my desired answer, but when I use for loop I keep getting the error如果我在没有循环的情况下运行程序,我会得到我想要的答案,但是当我使用 for 循环时,我会不断收到错误

(dictConcepts[a_string[0], a_string[2].rstrip('\n')] = a_string[1] (dictConcepts[a_string[0], a_string[2].rstrip('\n')] = a_string[1]
IndexError: list index out of range) IndexError:列表索引超出范围)

This is my code:这是我的代码:

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])

Right now, if:现在,如果:

a_string = anyLine(name, i).split('\t')

does not produce at least a length three list, (ie \t is present twice in the line) your code will fail with an index error.不会产生至少长度为三的列表,(即\t在该行中出现两次)您的代码将因索引错误而失败。

You can program a try / except so you're not indexing things that do not exist:你可以编写一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM