【问题标题】:Why am I getting this "list index out of range" error?为什么我会收到此“列表索引超出范围”错误?
【发布时间】:2020-10-11 18:25:54
【问题描述】:

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

【问题讨论】:

  • 抛出错误的行中有三个索引操作。显然,其中之一超出了界限。您必须提供minimal reproducible example。老实说,您需要最少努力自己调试...您是否尝试过查看a_string 实际上是什么?

标签: python loops dictionary index-error


【解决方案1】:

现在,如果:

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

【讨论】:

  • mabye print('something is not right here, expected 3 items, got', a_string)
  • @juanpa.arrivillaga 是的,无论程序员想放什么——只是一般的想法!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-22
  • 2011-11-30
  • 1970-01-01
  • 2017-12-02
相关资源
最近更新 更多