行平均CSV Python [英] Row Average CSV Python

查看:1476
本文介绍了行平均CSV Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个代码,它将打印来自csv的每个用户分数的平均值。



它需要读取所有分数,然后计算出平均值



它还需要计算有多少分数才能准确计算出平均分,所以如果只有2个测试完成然后需要

  STUDENT,SCORE1, SCORE2,SCORE3 
elliott,12,2,12
bob,0,11,1
test,0,1

我需要代码来计算所有用户在CSV中的平均值,然后打印输出。



Cheers。

解决方案

您可以使用 csv library 来读取文件。这是只是一个计算平均值的情况:

  import csv 

with open .csv')as handle:
reader = csv.reader(handle)
next(reader,None)
读取行中的行:
user,* scores = row
average = sum([int(score)for score in scores])/ len(scores)
print(
{user}平均值=平均值)


$ b

  elliott平均值为8.666666666666666 
bob平均值为4.0
测试平均值为0.5

此代码需要python 3。


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.

这篇关于行平均CSV Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆