|
发表于 2023-5-29 18:55:48
|
显示全部楼层
本楼为最佳答案
你的代码的问题是由于你试图从空列表中取值导致的。问题在这部分代码:
with open('score.csv','r') as score:
reader = csv.reader(score)
print(list(reader))
s1 = [row[1] for row in list(reader)]
s2 = [row[2] for row in list(reader)]
s3 = [row[3] for row in list(reader)]
你调用了 list(reader) 三次。第一次调用打印了整个列表,而在其后两次调用中,你试图从这个已经被遍历完的reader对象中获取元素,这就是为什么s1、s2和s3都是空的,因为在这时reader对象已经没有任何数据了。
换句话说,reader对象是一个迭代器,当你遍历它一次后,你就不能再从中获取数据了。
你可以像下面这样修改你的代码:
with open('score.csv','r') as score:
reader = csv.reader(score)
all_rows = list(reader) # 只调用一次list(reader)
print(all_rows)
s1 = [row[1] for row in all_rows]
s2 = [row[2] for row in all_rows]
s3 = [row[3] for row in all_rows]
现在,s1、s2和s3将包含你想要的数据,因为我们只对reader对象调用一次 list() 函数,以获取其所有行。这样,当我们进行后续处理时,就可以从这个列表中获取数据了。
修改后的完整代码:import csv
score1 = [['考号','程序设计','细胞生物','生理学'],[10153450101,72,96,88],[10153450102,68,88,73],[10153450103,63,63,66],[10153450104,95,64,65],[10153450105,89,88,57],[10153450106,77,87,77],[10153450107,67,64,97],[10153450108,44,99,64],[10153450109,82,73,75],[10153450110,79,78,85]]
with open ('score.csv','w',newline='') as score:
writer = csv.writer(score)
for row in score1:
writer.writerow(row)
with open('score.csv','r') as score:
reader = csv.reader(score)
all_rows = list(reader) # 只调用一次list(reader)
s1 = [row[1] for row in list(all_rows)]
s2 = [row[2] for row in list(all_rows)]
s3 = [row[3] for row in list(all_rows)]
S = [s1,s2,s3]
for s in S:
Sum = 0
print('{}:'.format(s[0]),end='')
for i in s[1:]:
Sum += int(i)
|
|