如何计算平均值,将其写入CSV文件,然后使用python对其进行排序

时间:2015-12-23 12:44:58

标签: python csv

我试图让我的函数计算出平均值,将其写入文件并使用python对其进行排序。这是我的代码:

def average_score(filename):

    with open(filename) as Class:
        reader = c.reader(Class,delimiter=",")
        for row in reader:
            people = []
            people.append(row[0])
            user, *scores = row
            average = sum([int(score) for score in scores]) / len(scores)
            a = open(filename,"a").writer(Class)

            data = [[average]]

            a.writerows(data)
            people.append(score)

            count = count+1
            list11.insert(count,people)

    sort=sorted(list11, key = o.itemgetter(4), reverse = False)
    for eachline in sort:
        print( eachline)

csv文件:

kieran,3,10,7
ben,4,8,5
ethan,9,1,4
oliver,7,2,3

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效

def average_score(filename):

    averages = {}
    with open(filename) as fd:
      reader = c.reader(fd, delimiter=",")

      for row in reader:
        user, *scores = row

        # the user has no score
        if len(scores) == 0:
           continue

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

    sorted_averages = sorted(averages.items(), key = o.itemgetter(1), reverse = False)

    # This writes the average to the file, remove if necessary
    with open(filename, 'a') as fd:
      for item in sorted_averages:
        fd.write("{}: {}\n".format(item[0], item[1]))

    # This prints out to screen, remove if necessary
    for item in sorted_averages:
        print("{}: {}".format(item[0], item[1]))