Python:读取和分析CSV文件 [英] Python: reading and analyzing CSV files
问题描述
我有一个CSV文件,其中包含学生姓名及其8个科目的平均值.我必须计算出哪些学生荣登荣誉榜(总体平均成绩达到80分或以上),哪些学生获得了该学科的奖项(每个学科的最高分).我已经完成了荣誉榜部分,并且可以正常工作,但是我无法使主题奖部分发挥作用.我将如何使它工作?我想不通!
I have a CSV file with student names and their averages for 8 subjects. I have to calculate which students made the honour roll (OVERALL average of 80 or above) and which students got the subject award (highest mark in each subject). I have done the honour roll part, and it works, but I can't get the subject award part to work. How would I get this to work? I can't figure it out!
这是我的代码:
import csv
with open('C:/Users/rohan/Desktop/Google Drive/honourCSVreader/honour.csv')
as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
# Honour Roll
print('The honour roll students are:')
for col in csv_reader:
if not col[0] or col[1]:
for row in csv_reader:
if (int(row[2]) + int(row[3]) + int(row[4]) + int(row[5]) +
int(row[6]) + int(row[7]) + int(row[8]) + int(row[9])) / 8
>= 80:
print(row[1] + " " + row[0])
# Subject Awards
print('The subject award winners are:')
for col in csv_reader:
if not col[0] and not col[1]:
name = []
maximum_grade = 0
subject = []
for col[2:] in csv_reader:
if col > maximum_grade:
subject = row
maximum_grade = col
name = [col[1], col[0]]
print(str(name) + ' - ' + str(subject))
这是荣誉"文件(学生名单): https://1drv.ms /x/s!AhndVfox8v67iggaLRaK7LTpxBQt
And here is the 'honour' file (list of students): https://1drv.ms/x/s!AhndVfox8v67iggaLRaK7LTpxBQt
谢谢!
推荐答案
与@edilio合作,我制作了一个更有效的版本,可以保持联系.其中有很多,所以这是一个非常重要的区别.该代码很长,因此我将在主要内容上进行托管.
In collaboration with @edilio I've made a more efficient version that keeps track of ties. There are many of these so it's a rather important distinction. The code is long so I'll host it on a gist.
https://gist.github.com/SamyBencherif/fde7c3bca702545dd22739dd8caf796a
不需要for
循环.实际上,第二个for循环中的语法完全被破坏了.
No need for for
loops. In fact the syntax in your second for loop was totally botched.
import csv
with open('C:/Users/rohan/Desktop/Google Drive/honourCSVreader/honour.csv')
as csv_file:
csv_list = list(csv.reader(csv_file, delimiter=","))[1:]
# Subject Awards
print('The subject award winners are:')
print('English', max(csv_list, key=lambda row: row[2]))
print('Math', max(csv_list, key=lambda row: row[3]))
print('Geography', max(csv_list, key=lambda row: row[4]))
以此类推
这篇关于Python:读取和分析CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!