首页 > 解决方案 > Python - 对包含字符串和整数的列表进行排序

问题描述

这是我的代码:


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

所以这是我的代码,对于这个游戏中的排行榜功能,我想将列表(包含字符串 - 用户名和整数 - 分数)按分数(整数)的降序排列。它看起来像这样:

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

之后: Player2:98 Player1:34 Player3:22

有谁知道谁来做这个?

标签: python-3.xsorting

解决方案


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]}')

推荐阅读