首页 > 解决方案 > 无法在python中插入二维列表

问题描述

我正在尝试将一个元素插入从文本文件读取的数据表中每一行的第一列。

grades = [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],
               [0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],
               [0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]]
student = ["Alice Arnold", "Cory Brown", "Sean Douglas", "Pete Douglas", "Mary Fleming", "Joel Jacob",
               "Jeramy Ghouse", "Hansie Holder", "Loyola Ingenious", "Gary Jackson", "Russell Jacobson",
               "Dustan Kellart", "Carl Melone" , "Samuel Peterson", "Alec Stewart"]
code = ""
s=0
for i in file:
    pos = 9
   
    code = file.read(pos)
    info = code.split("\n")
    indexRow = info.pop()
    row = int(indexRow[0:2])   #slice the first 2 digits for row index
    col = int(indexRow[2:4])   #slice the other 2 digits for the column index 
    gr = float(indexRow[5:9])   #slice the grade
    grades[row][col] = gr
    grades[row][0] = student[s]
    s+=1

文本文件有两列,一列是四位代码,必须分解为二维列表中位置的适当索引。另一个是等级。每行是一个学生的成绩,我想在每行第 0 列的列表开头插入他的名字。

我认为grades[row][0] = student[s]这是将项目插入列表的合法方式,但我一直收到此行的错误“IndexError:列表索引超出范围”。任何事情都值得赞赏。

标签: pythonlistinsert

解决方案


您需要使用索引而不是理解来使用 for 循环

for i in range(len(inputList()):

推荐阅读