我在Python中製作了混亂的文字遊戲,現在我想將分數從高到低排序。對於記錄分數,我使用擱置,但現在我不知道如何將它們排序爲關鍵時使用擱置必須是一個字符串。我知道我可以使用泡菜,但如果有人知道,有沒有什麼辦法可以解決這個擱置? 謝謝你的幫助!使用擱置鍵對分數進行排序
def game():
shelf=shelve.open("wordlists.dat")
listname = list(shelf.keys())
for i in listname:
print("{}--{}".format(listname.index(i)+1,i))
choice = int(input("Pick one:"))
word_set=(listname[choice-1])
global wordlist
wordlist = shelf[word_set]
score = 0
#Choosing a random word from the wordlist
for i in range(4):
word = random.choice(wordlist)
theWord = word
jumble = ""
#Jumbling the word
while(len(word) > 0):
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[position + 1:]
print("The jumble word is: {}".format(jumble))
# Getting player's guess
guess = input("Enter your guess: ").lower()
# Congratulate the player
if(guess == theWord):
print("Congratulations! You guessed it")
score += 1
else:
print("Sorry, wrong guess.")
#Printing the score
print("You got {} out of 10".format(score))
#Recording the score
shelf = shelve.open("score.dat")
score = str(score)
shelf.sync()
shelf.close()
return menu()
def score():
myformat = "{:10s} {:13s}"
print(myformat.format('Score', 'Date'))
print("-"*26)
shelf = shelve.open("score.dat")
for key in shelf.keys():
dates = shelf[key]
for val in dates:
print(myformat.format(key, val))
shelf.close
輸出:
Score Date
--------------------------
0 Wed Nov 16 12:07:28 2016
2 Wed Nov 16 12:16:14 2016
4 Wed Nov 16 12:16:42 2016
1 Wed Nov 16 12:01:19 2016
貨架基本上只是持續的字典,和他們一樣,不能進行排序(和無關的鑰匙需要以是字符串)。您可以做的最好的方式是獲取所有鍵的列表,對其進行排序,然後使用它按排序順序訪問相應的值。實際上,你可能只是使用一個普通字典和'pickle'來保存和恢復它。 – martineau