[英]store last 3 scores with the use of pickle or json?
我进行了一个测验,允许用户输入他们的姓名,并根据他们所在的班级将他们的姓名和分数保存到特定文件中。但是,我需要该文件仅存储最近的3个分数。 我已经显示了以下尝试之一,但它仍然不会只存储3个最新分数。 我已经研究了其他方法,并且意识到我可能需要泡菜或json才能将3_scores的内容写入文本文件? 所以我想如果你们中的一个可以解释,并且可能在需要时使用pickle或json编写解决方案,因为我已经尝试过并且仍然无法做到。
if classselection ==1:
File=open("1.txt","a")
File.write(names+","+str(score)+"\n")
File.close()
classselection=str(classselection)
with open("1.txt" , "a") as my_class:
my_class.write(names+","+str(score)+"\n")
with open("1.txt" , "r+")as file:
file.seek(0)
scores = file.readlines()
3_scores = {}
for line in scores:
names, score = line.split(',')
score = int(score)
if names not in 3_scores:
3_scores[names] = []
3_scores[names].append(score)
if len(3_scores[names]) > 3:
3_scores[names].pop(0)
然后,我尝试使用json,所以在上面的代码写完之后
import json
d=user_scores
json.dump(d,open('A.txt','w'))
d2=json.load(open('A.txt'))
print (d2)
但是,这没有作为
names, score = line.split(',')
ValueError: too many values to unpack (expected 2)
现在编辑嗨,打印的是
{' lol': [5]}
{' sid': [8], ' lol': [5]}
{' sid': [8, 8], ' lol': [5]}
{' lok': [1], ' sid': [8, 8], ' lol': [5]}
{' lok': [1, 1], ' sid': [8, 8], ' lol': [5]}
{' lok': [1, 1], ' sid': [8, 8], ' lojhg': [0], ' lol': [5]}
{' lok': [1, 1], ' sid': [8, 8], ' lojhg': [0, 0], ' lol': [5]}
这是不对的。 所以请,如果有人可以提供解决方案,我将不胜感激
**此外,在文本文件中它可能会说
sid ,1
sid ,6
sid ,3
sid ,10
sid ,4
但我只想存储
sid ,3
sid ,10
sid ,4
另外,如果这不是很麻烦,有谁知道我该如何将同一个人的结果水平存储在其名字旁边。
sid(3,10,4)
****如果一个名叫gary的用户完成了5次测验并获得2、4、3、5、7分,那么一次输入adxpete输出的示例便是一次,名字gary和他获得的分写入文本文件。 但是当分数达到5(第四次gary完成测验)时,最早的2分被删除,因此txt文件中gary的分数只有3。
这是使用pickle
的解决方案。
请注意,对于大型数据集来说,泡菜不是最安全的选择,也不是最好的选择,但它很容易。 对于具有适当前端的SQL,将更适合。 我假设您在本地计算机上只有几个用户。
要创建我们的泡菜对象(只需执行一次):
import pickle
name = 'sid'
scores = [10,7,8]
data = {} # dictionary object is well suited for named data
data[name] = scores
with open("out.pickle","wb") as f:
pickle.dump(data, f) # saves to cwd
创建后,以下功能将根据您的要求将信息添加到腌制对象中:
def add_score(name, score, filename="out.pickle"):
""" """
# open our 'database'
with open(filename, "rb") as f:
data = pickle.load(f)
# if we already have an entry under this name, add to it.
# if we don't, create a new one
if name in data.keys():
if len(data[name]) > 2: # as we have a maximum length of three
old_score = data[name].pop(0) # removes the first score
data[name].append(score)
else:
data[name] = [score]
with open(filename, "wb") as f:
pickle.dump(data, f)
return data
有关此示例的示例:
>>> d = add_score('sid',11)
>>> d
{'sid': [7, 8, 11]}
>>> d = add_score('sid',14)
>>> d
{'sid': [8, 11, 14]}
>>>
>>> d = add_score('roger',10)
>>> d
{'sid': [7, 8, 14], 'roger': [10]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.