绝对初学者的 Python 编程第 7 章挑战 2
我一直在尝试使用这本书来学习Python,但是,我似乎陷入了这个挑战。
“2. 改进 Trivia Challenge 游戏,使其在文件中维护高分列表。如果玩家进入列表,程序应记录玩家的姓名和分数。使用 pickled 对象存储高分。”
我决定使用列表而不是字典,因为我认为我无法对字典分数进行排序。但是,要根据您的问题更新字典版本,当您加载字典时,请为其提供另一个变量,然后将该变量添加到原始变量中。
所以它会是这样的:
首先我创建了一个空白列表来保存字典。
high_scores = []
然后运行一个单独的程序来更新分数。
new_score = {score: player}
f = open("high_Scores.txt", "rb")
score_list = high_scores
f.close()
score_list.append(new_score)
score_list = score_list[:10]
f = open("high_scores.txt", "wb")
pickle.dump(score_list, f)
f.close()
这仅保存 10 个分数,并将更新字典。我还没弄清楚如何排序 分数和阅读我认为在本书的这一点上是不可能的。 我正在考虑切换到列表或其他东西。我还没有真正从事过这方面的工作,所以目前我还不确定。如果你弄清楚了请告诉我。
I've been trying to learn python using this book, however, I seem to be stuck on this challenge.
"2. Improve the Trivia Challenge game so that it maintains a high-scores list in a file. The program should record the player's name and score if the player makes the list. Store the high scores using a pickled object."
I decided to use lists instead of dictionaries because I don't think I can sort the dictionary scores. However, to update the dictionary version per your question, when you load the dictionary give it another variable and then add that variable to the original.
so it would go something like this:
first I created a blank list to hold the dictionary.
high_scores = []
then run a separate program to update the scores.
new_score = {score: player}
f = open("high_Scores.txt", "rb")
score_list = high_scores
f.close()
score_list.append(new_score)
score_list = score_list[:10]
f = open("high_scores.txt", "wb")
pickle.dump(score_list, f)
f.close()
this only holds 10 scores and will update the dictionary. I haven't figured out how to sort
the scores and from reading I don't think it's possible to do at this point in the book.
I was thinking of switching over to lists or something. I haven't really worked on it so I'm not sure at this point. if you figure it out let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不想为你做这一切,但这里有一些提示:
不需要字典,字典是无序的。使用二元组的排序列表:
high_scores = [(score1, name1), (score2, name2), ...]
。按相反顺序对列表进行排序:high_scores.sort(reverse=True)
。使用list
append
和pop
方法添加新条目并删除不再位于前十名的条目。I don't want to do it all for you, but here are some hints:
No need for dictionary, dictionaries are unordered. Use a sorted list of 2-tuples:
high_scores = [(score1, name1), (score2, name2), ...]
. Sort the list in reverse order:high_scores.sort(reverse=True)
. Use thelist
append
andpop
methods to add new entries and remove entries which are no longer in the top ten.