【问题标题】:Python - index out of range errorPython - 索引超出范围错误
【发布时间】:2016-04-17 03:28:19
【问题描述】:

这是我最近的代码:

highest = {}
def reader():
    myfile = open("scores.txt","r")
    pre = myfile.readlines()

    print(pre)


    for line in pre :
       print(line)
       x = line.split(",")

       a = x[0]

       b = x[1]

       c = len(b)-1
       b = b[0:c]

       highest[a] = b

这是完整的 Traceback 错误消息:

 Traceback (most recent call last):
        File "C:/Python34/my boto snaky/snaky.py", line 568, in gameLoop
        reader()
        File "C:/Python34/my boto snaky/snaky.py", line 531, in reader
        b = x[1]
        IndexError: list index out of range

【问题讨论】:

  • 您在 scores.txt 中的某些行中没有逗号 (',')。另外,使用更好的标题。
  • 这真的是你能想到的最具描述性的标题吗?
  • 它说错误。 “列表索引超出范围”。您的某些行中没有逗号或缺少数据。
  • 实际上他们确实有逗号我认为问题是每个分数之间的空行但我真的不知道如何解决这个问题
  • @AnihsEmma: "actually they do have commas""the issue is the empty lines" 是相互排斥的陈述。空行不会有逗号,因此会出现错误。

标签: python


【解决方案1】:

您在 scores.txt 中的某些行没有逗号。你可以检查那些:

if len(x) == 1 : #there is no comma
    continue #ignore line and go to the next one

此代码将忽略不带逗号的行。把它放在计算 x = line.split(',') 之后。

如果您只想跳过空行,则相同:

if line.strip() == '': #remove whitespace then check if line is empty
    continue

【讨论】:

    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多