首页 > 解决方案 > 列表:索引超出范围

问题描述

这是我的代码:

if __name__ == '__main__':
    n = int(input())
    for i in range(n):
        name = input()
        score = float(input())
        python_students = [[name, score]]
    z=len(python_students)
    for i in range(z):
        if python_students[i][1]<python_students[i+1][1]:
            list = [python_students[1]]
        list.sort()
        print(list)  

error : Traceback (most recent call last):
  File "solution.py", line 9, in <module>
    if python_students[i][1]<python_students[i+1][1]:
IndexError: list index out of range

我真的对这种类型的错误感到困惑,请解释并帮助我处理这段代码。

我正在尝试从列表中按字母顺序获取名称

标签: pythonlistindexoutofboundsexception

解决方案


z应该是len(python_students)-1。在最后一次迭代中,python_students[i+1][1]超出了列表的范围。


推荐阅读