Skip to main content
 首页 » 编程设计

Python:只保存三个最新分数

2024年10月25日11java哥

这是我为 children 做的小测验。该程序的主体工作正常。但它必须将每个用户的三个最新的 correctAnswers 保存到一个 .txt 文件中,删除旧的分数。

我花了很多时间尝试弄清楚如何将 JSON 或 Pickle 用于我的代码,但我不知道如何将它们用于我的代码。任何帮助将不胜感激。

if usersGroup == a: 
    with open("groupA.txt","a+") as f: 
        f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken)) 
 
elif usersGroup == b: 
    with open("groupB.txt","a+") as f: 
        f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken)) 
 
elif usersGroup == c: 
    with open("groupC.txt","a+") as f: 
        f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken)) 
else: 
    print("Sorry, we can not save your data as the group you entered is not valid.") 

请您参考如下方法:

如果您同时更新三个分数,则需要覆盖而不是追加:

open("groupA.txt","w")  

要保留上次运行的最后两个并写入最新的单个分数:

with open("groupA.txt","a+") as f: 
    sores = f.readlines()[-2:] # get last two previous lines 
    with open("groupA.txt","w") as f: 
        # write previous 2 
        f.writelines(scores) 
        # write latest 
        f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken)) 

可能更容易 pickle 或 json a dict 并保留一个分数列表,用最新分数替换最后一个分数。

import pickle 
from collections import defaultdict 
 
with open('scores.pickle', 'ab') as f: 
    try: 
        scores = pickle.load(f) 
    except ValueError: 
       scores = defaultdict(list)  
 
    # do your logic replacing last score for each name or adding names 
 
   with open('scores.pickle', 'wb') as f: 
       # pickle updated dict  
       pickle.dump(f,scores) 

如果你想要人类可读的格式使用 json.dump 和一个普通的字典,你可以使用 dict.setdefault 而不是使用 defaultdict 的功能:

import json 
 
 
with open('scores.json', 'a') as f: 
    try: 
        scores = json.load(f) 
    except ValueError: 
        scores = {} 
        # add user if not already in the dict with a list as a value 
        scores.setdefault(name,[]) 
         # just append the latest score making sure when you have three to relace the last 
        scores[name].append(whatever) 
 #   do your logic replacing last score for each name or adding names 
 
    with open('scores.json', 'w') as f: 
       json.dump(scores,f)