Python-对包含字符串和整数的列表进行排序

时间:2019-09-28 14:30:44

标签: python-3.x sorting

这是我的代码:


猜歌V2

import random

import time

def Game():

x = 0

#AUTHENTICATION
Username = input("What is your username?")
#Asking for an input of the password.
Password = str(input("What is the password?"))

#If password is correct then allow user to continue.
if Password == "":
    print("User Authenticated")

#If not then tell the user and stop the program
elif Password != "":
    print("Password Denied")
    exit()

#GAME
#Creating a score variable
score=0

#Reading song names and artist from the file
read = open("Song.txt", "r")
songs = read.readlines()
songlist = []

#Removing the 'new line' code
for i in range(len(songs)):
        songlist.append(songs[i].strip('\n'))

while x == 0:
        #Randomly choosing a song and artist from the list
        choice = random.choice(songlist)
        artist, song = choice.split('-')

        #Splitting the song into the first letters of each word
        songs = song.split()
        letters = [word[0] for word in songs]

        #Loop for guessing the answer
        for x in range(0,2):
            print(artist, "".join(letters))
            guess = str(input("Guess the song : "))
            if guess == song:
                if x == 0:
                    score = score + 3
                    break
                    if x == 1:
                        score = score + 1
                        break

        #Printing score, then waiting to start loop again.
        print("Your score is", score)
        print("Be ready for the next one!")
        score = int(score)

leaderboard = open("Score.txt", "a+")
score = str(score)
leaderboard.write(Username + ' : ' + score + '\n')
leaderboard.close()

leaderboard = open("Score.txt", "r")
#leaderboardlist = leaderboard.readlines()
Scorelist = leaderboard.readlines()
for row in Scorelist:
    Username, Score = row.split(' : ')
    Score = int(Score)
    Score = sorted(Score)
leaderboard.close()
Game()

这是我的代码,对于此游戏中的排行榜功能,我想将列表(同时包含字符串-用户名和Interger-Score)按得分(Interger)的降序排列。看起来像这样:

之前:        玩家1:34        玩家2:98        玩家3:22

之后:        玩家2:98        玩家1:34        玩家3:22

有人知道该怎么做吗?

1 个答案:

答案 0 :(得分:0)

scores = {}
for row in score_list:
  user, score = row.split(':')
  scores[user] = int(score)

highest_ranking_users = sorted(scores, key=lambda x: scores[x], reverse=True)

for user in highest_ranking_users:
  print(f'{user} : {score[user]}')
相关问题