简体   繁体   English

无法插入 python 中的二维列表

[英]Unable to insert into 2d list in python

I am trying to insert an element into the first column of each row in a table of data read from a text file.我正在尝试将一个元素插入从文本文件读取的数据表中每一行的第一列。

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

The text file has two columns, one is a four digit code that must be broken down into proper indices for the position in the 2d list.文本文件有两列,一列是四位代码,必须将其分解为二维列表中 position 的正确索引。 The other is a grade.另一个是等级。 Each row is a student's grades, whose name I want to insert at the beginning of the list at column 0 of each row.每行是一个学生的成绩,我想在每行第 0 列的列表开头插入他的名字。

I thought grades[row][0] = student[s] was the legal way to insert an item into a list, but I keep getting the error "IndexError: list index out of range" for this line.我认为grades[row][0] = student[s]是将项目插入列表的合法方式,但我一直收到此行的错误“IndexError:list index out of range”。 Anything is appreciated.任何事情都值得赞赏。

You need to use for loop using index rather then comprehension您需要使用索引而不是理解来使用 for 循环

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

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

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