使用sh按键排序分数

2024-09-29 23:27:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python做了一个混乱的单词游戏,现在我想把分数从高到低排序。为了记录分数,我用shelve,但现在我不知道如何将它们排序,因为使用shelve必须是一个字符串。我知道我可以用泡菜,但是如果有人知道的话,有没有办法用shelve解决这个问题? 谢谢你的帮助!在

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

输出:

^{pr2}$

Tags: theinformatforpositionopenshelveword
1条回答
网友
1楼 · 发布于 2024-09-29 23:27:20

我想出来了。我把钥匙放进一个单子里,然后用泡泡分类。 这是最终代码:

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()

输出:

^{pr2}$

相关问题 更多 >

    热门问题