2016-11-16 32 views
0

我在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 
+1

貨架基本上只是持續的字典,和他們一樣,不能進行排序(和無關的鑰匙需要以是字符串)。您可以做的最好的方式是獲取所有鍵的列表,對其進行排序,然後使用它按排序順序訪問相應的值。實際上,你可能只是使用一個普通字典和'pickle'來保存和恢復它。 – martineau

回答

-1

我想通了。我把鑰匙放入一個列表中,並將它排序。 這是最後的代碼:

def score(): 
    myformat = "{:10s} {:13s}" 
    print(myformat.format('Score', 'Date')) 
    print("-"*26) 
    shelf = shelve.open("score.dat") 
    listname = list(shelf.keys()) 
    #print(listname) 
    for num in range(len(listname)-1,0,-1): 
     for i in range(num): 
      if listname[i]>listname[i+1]: 
       temp = listname[i] 
       listname[i] = listname[i+1] 
       listname[i+1] = temp 
    for key in listname: 
     dates = shelf[key] 
     for val in dates: 
      print(myformat.format(key, val)) 
    shelf.close 
    return menu() 

輸出:

Score  Date   
-------------------------- 
0   Wed Nov 16 18:08:53 2016 
1   Wed Nov 16 18:04:57 2016 
2   Wed Nov 16 18:05:11 2016 
3   Wed Nov 16 18:05:44 2016 
4   Wed Nov 16 18:04:44 2016 
+0

'list.sort()'會爲你排序...你甚至可以指定[它應該如何排序](http://stackoverflow.com/questions/36139/how-do-i-sort-a-list -of串式的Python)。 – TemporalWolf

+0

你已經有了基本的想法,但正如@TemporalWolf所指出的那樣,最好使用Python內置的排序方法之一,除了已經被編寫和調試之外,它們都比泡泡排序更快。 – martineau

+0

是的,我知道。但作爲一名Python初學者,我仍然在學習,並希望使用另一種方式而不是內置方法。 –