移动 along/replace 某些行 csv python

move along/replace certain rows csv python

我有一个用于测验的 csv 文件,如下所示

name,score1,score2,score3,highest,avg
foo,4,10,7,10,10.3
bar,6,4,9,9,6.3
baz,8,4,6,8,6

我的问题是,当 foo 下一次参加测验时,我该如何将分数向左移动一位,分数 1 被所述测试的分数和分数 3 代替被删除,同时更新最高和平均。我尝试了很多不同的方法,但我无法弄清楚

编辑:

post-修改,假设 foo 得分为 6,baz 得分为 2,我希望文件显示

foo,6,4,10,10,3.6
baz,2,8,4,8,4.6

我尝试将行附加到字典中,但无法弄清楚如何独立修改分数

由于您没有提供任何代码作为起点,因此很难为您提供帮助。以下代码将采用 CSV,检查第一列中的名称和分数,并使用新分数更新相应的行:

import csv

def update_scores(name, new_score):
    new_file = []    # This will hold our information for later (since we can't both read and write simultaneously)
    with open('scores.csv', 'rb') as f:
        reader = csv.reader(f)
        for line in reader:
            if line[0] == name:    # We have found the row that matches the name we put in
                highest = max(int(new_score), int(line[1]), int(line[2]))   # Form the new highest score
                avg = round((int(new_score) + int(line[1]) + int(line[2])) / 3.00, 2)    # Form the new average score
                new_file.append([line[0], new_score, line[1], line[2], highest, avg])    # Write all of this new information to our new_file
            else:
                new_file.append(line)    # If the line doesn't need to be updated, just add it to our new_file

    with open('scores.csv', 'wb') as f:
        writer = csv.writer(f)
        for line in new_file:    # Write all of our new information back into the new file.
            writer.writerow(line)

update_scores('foo', '4')   # Send in the name and it's newest score

我对你计算平均值的方式感到困惑。例如,10.3 不是 4、10 和 7 的平均值。对于我的回答,我假设您只想要三个分数的平均值:

import csv

def update_scores(new_scores):
    rows = []
    with open('quiz.csv', 'r') as f:
        reader = csv.reader(f)
        next(reader)        
        for row in reader:
            if row[0] in new_scores:
                updated_scores = [new_scores[row[0]], int(row[1]), int(row[2])]
                highest = max(updated_scores)
                avg = sum(updated_scores) / float(len(updated_scores))
                rows.append([row[0]] + updated_scores + [highest, '%.1f' % avg])
            else:
                rows.append(row)
    with open('quiz.csv', 'w') as f:
        writer = csv.writer(f)
        writer.writerow(['name','score1','score2','score3','highest','avg'])
        writer.writerows(rows)

if __name__ == '__main__':
    new_scores = {'foo': 6, 'baz': 2}
    update_scores(new_scores)

输出:

name,score1,score2,score3,highest,avg
foo,6,4,10,10,6.7
bar,6,4,9,9,6.3
baz,2,8,4,8,4.7