简体   繁体   English

如何修复列表索引超出范围?

[英]How to fix list index out of range?

I am having problems with this line.我遇到了这条线的问题。 I am not really sure why it gives me list index out of range.我不太确定为什么它让我的列表索引超出范围。 I've tried couple of solutions so far none of them worked.到目前为止,我已经尝试了几种解决方案,但都没有奏效。

scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
# Print first 5
a = 0
for score in scoreboardSorted:
    print(str(score[0]) + ": " + str(score[1]) + " points")
    a = a + 1
    if a == 5:

This is the full section of this code这是此代码的完整部分

def endGame(points):
    scoreboard = []
    # Write score to scoreboard
    with open("scoreboard.csv", "a") as scoreboardFile:
        scoreboardWriter = csv.writer(scoreboardFile)
        scoreboardWriter.writerow([name, points])
    # Open scoreboard in read mode and store in memory
    scoreboardFile = open("scoreboard.csv", "rt")
    scoreboardReader = csv.reader(scoreboardFile)
    for i in scoreboardReader:
        scoreboard.append(i)
    print("\nGame over!")
    print("Well done " + str(name) + ", you got " + str(points) + " points.")
    print("\nTop 5:")
    # Sort list
    scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
    # Print first 5
    a = 0
    for score in scoreboardSorted:
        print(str(score[0]) + ": " + str(score[1]) + " points")
        a = a + 1
        if a == 5:
            break
    sys.exit()

The traceback is this追溯是这个

Traceback (most recent call last):
  File "E:\Nea\NEA-PROJECT.py", line 128, in <module>
    endGame(points)
  File "E:\Nea\NEA-PROJECT.py", line 30, in endGame
    scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
  File "E:\Nea\NEA-PROJECT.py", line 30, in <lambda>
    scoreboardSorted = sorted(scoreboard, key = lambda t: t[1], reverse = True)
IndexError: list index out of range

PS: Please do not just post solutions and actually explain in detail. PS:请不要只是发布解决方案并实际详细说明。 I am a student in secondary school who is still trying to learn and I would really appreciate it if u take your time and explain it.我是一名仍在努力学习的中学学生,如果您能花时间解释一下,我将不胜感激。 Thanks in advance.提前致谢。

Your scoreboard is missing data.您的scoreboard缺少数据。 For example, the second row in the table below is missing its second value.例如,下表中的第二行缺少其第二个值。

a = [[1, 2], [3,], [5, 6]]
>>> sorted(a, key=lambda t: t[1])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-341-fea6d7792ad0> in <module>
      1 a = [[1, 2], [3,], [5, 6]]
----> 2 sorted(a, key=lambda t: t[1])

<ipython-input-341-fea6d7792ad0> in <lambda>(t)
      1 a = [[1, 2], [3,], [5, 6]]
----> 2 sorted(a, key=lambda t: t[1])

IndexError: list index out of range

You could use a ternary to give missing values a default, eg zero.您可以使用三元为缺失值提供默认值,例如零。

>>> sorted(a, key=lambda t: t[1] if len(t) > 1 else 0)
[[3], [1, 2], [5, 6]]

t[1] in your lambda function is impossible if t (an item in scoreboard ) has less than 2 values (1 or 0).如果tscoreboard中的项目)少于 2 个值(1 或 0),则 lambda function 中的t[1]是不可能的。 This probably means you have too few values in your csv file.这可能意味着您的 csv 文件中的值太少。

Either you fix the values in your csv or you fallback on some default value when sorting:要么修复 csv 中的值,要么在排序时使用一些默认值:

scoreboardSorted = sorted(scoreboard, key = lambda t: t[1] if len(t) > 1 else 0, reverse = True)

Note that I used 0 as the default here but if that gives you the wrong sorted order or a type error you'll have to figure out another suitable value as the default.请注意,我在这里使用0作为默认值,但如果这给您错误的排序顺序或类型错误,您将不得不找出另一个合适的值作为默认值。

sorted(scoreboard, key=lambda t: t[1], reverse=True)

This assumes that each item in scoreboards is itself a sequence of at least two items.这假设scoreboards中的每个项目本身都是至少两个项目的序列。

It sounds like there is least one item in scoreboards that has fewer than two items.听起来scoreboards中至少有一项少于两项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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