python求csv平均值,行平均CSV Python

Im looking for a piece of code that will print the average for each users score from a csv.

It needs to read all scores and then work out an average across the row for each users.

It also needs to calculate how many scores there are to accurately work out the average score so if there are only 2 tests completed it then needs divide by 2.

The CSV is

STUDENT,SCORE1,SCORE2,SCORE3

elliott,12,2,12

bob,0,11,1

test,0,1

I need the code to work out all users averages as described above in the CSV and then print the output.

Cheers.

解决方案

You can use the csv library to read the file. It is then just a case of calculating the averages:

import csv

with open('example.csv') as handle:

reader = csv.reader(handle)

next(reader, None)

for row in reader:

user, *scores = row

average = sum([int(score) for score in scores]) / len(scores)

print (

"{user} has average of {average}".format(user=user, average=average)

)

With your input this prints:

elliott has average of 8.666666666666666

bob has average of 4.0

test has average of 0.5

This code requires python 3.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值