我对python很新。我编写了一个程序,可以在pickle字典对象中保存高分,然后调用它。我有一些关于我的计划的问题,也许有人可以帮助我。
-
import pickle
high_scores = {"Adam Smith": 65536, "John Doe": 10000}
with open("highscores.pkl","wb") as out:
pickle.dump(high_scores, out)
new_score = (raw_input("Enter your name ").title(), int(raw_input("Enter your score ")))
with open("highscores.pkl","rb") as in_:
high_scores = pickle.load(in_)
if new_score[0] not in high_scores:
high_scores[new_score[0]] = new_score[1]
if new_score[0] in high_scores and new_score[1] not in high_scores.values():
high_scores[new_score[0]] = new_score[1]
else:
pass
with open("highscores.pkl","wb") as out:
pickle.dump(high_scores, out)
print("-" * 80)
for name, score in high_scores.items():
print("{{name:>{col_width}}} | {{score:<{col_width}}}".format(col_width=(80-3)//2).format(name=name, score=score))
答案 0 :(得分:2)
为什么程序会写出同一个人的新分数,无论其更高还是更低
您不能比较值,只需检查该值是否已存在。
您需要检查if new score is > old score
,然后将其存储在值中。
您需要首先load
对象然后执行检查,并在最后执行dump
,否则每次运行应用时都会覆盖相同的数据。
high_scores = {"Adam Smith": 65536, "John Doe": 10000}
with open("highscores.pkl","wb") as out:
pickle.dump(high_scores, out)
每次启动应用时,您都会覆盖上述数据。
您需要在应用程序启动时使用一些逻辑来检查是否有任何数据已经被腌制,如果您没有,这是第一次运行所以设置high_scores ={}
并添加更新的信息,如果有数据只是unpickle并测试存储的值对新的。
If the file "highscores.pkl" does not exist, high_score ={} else open the file for reading
Do your comparison check and finally pickle.dump to file.
答案 1 :(得分:2)
new_score[1] not in high_scores.values()
替换为new_score[1] > high_scores[new_score[0]]
,因为后者实际检查新分数是否高于旧分数答案 2 :(得分:2)
根据Padraic的建议,下面的代码会检查highscores.pkl
是否存在。如果是,则将内容解开为high_scores
,否则会为其分配两个默认分数。
从那里开始,在输入新分数后,我们会检查high_scores
中是否存在密钥(玩家姓名)。如果确实如此,并且新分数更高,则替换旧分数。如果密钥不存在,那么我们添加播放器和分数。
执行该检查后,通过写入high_scores
文件保存highscores.pkl
。
import pickle
import os
high_scores = {}
if os.path.isfile('highscores.pkl'):
with open("highscores.pkl", "rb") as f:
high_scores = pickle.load(f)
else:
high_scores = {"Adam Smith": 65536, "John Doe": 10000}
new_score = (raw_input("Enter your name ").title(), int(raw_input("Enter your score ")))
if new_score[0] in high_scores:
if new_score[1] > high_scores[new_score[0]]:
high_scores[new_score[0]] = new_score[1]
else:
high_scores[new_score[0]] = new_score[1]
with open("highscores.pkl","wb") as out:
pickle.dump(high_scores, out)
print("-" * 80)
for name, score in high_scores.items():
print("{{name:>{col_width}}} | {{score:<{col_width}}}".format(col_width=(80-3)//2).format(name=name, score=score))