gpt4 book ai didi

python - 通过循环取消 Python 字典?

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:37 24 4
gpt4 key购买 nike

我是 Python 的新手,我想要实现的是 pickle 字典,然后使用某种形式的循环(如果我的术语不正确,请见谅!)打印文件中的所有分数。

我正在使用 Python 3.3.3,这是我的尝试,用户输入一个名字和一个首先保存到文件中的分数,然后我尝试打印它。但是我无法打印分数。

import pickle

# store the scores in a pickled file
def save_scores(player, score):

f = open("high_score.dat", "ab")
d = {player:score}
pickle.dump(d, f)
f.close

# print all the scores from the file
def print_scores():

# this is the part that I can't get to work!
with open("high_score.dat", "r") as f:
try:
for player, score in pickle.load(f):
print("Player: ", player, " scored : ", score)
except EOFError:
pass
f.close

def main():

player_name = input("Enter a name: ")
player_score = input("Enter a score: ")

save_scores(player = player_name, score = player_score)
print_scores()


main()

input("\nPress the Enter key to exit")

我用 Google 搜索过 Stackoverflow 以查找类似问题,但我一定是使用了错误的术语,因为我还没有找到解决方案。

提前致谢。

最佳答案

pickle.load(f) 将返回一个字典。如果您迭代字典,它会生成键,而不是键值对。

要生成键值对,请使用 items() 方法(如果使用 Python 2.x,请使用 iteritems() 方法):

for player, score  in pickle.load(f).items():
print("Player: ", k, " scored : ", v)

要取出多个字典,需要循环:

with open("high_score.dat", "r") as f:
try:
while True:
for player, score in pickle.load(f).items():
# print("Player: ", k, " scored : ", v) # k, v - typo
print("Player: ", player, " scored : ", score)
except EOFError:
pass

顺便说一句,如果你使用with语句,你不需要自己关闭文件。

# f.close # This line is not necessary. BTW, the function call is missing `()`

关于python - 通过循环取消 Python 字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22173055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com