Python - сортировка списка, содержащего строку и интергер - PullRequest
0 голосов
/ 28 сентября 2019

Это мой код:


Guess Song 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 * ​​1010 *

После: Игрок2: 98 Игрок1: 34 Игрок3: 22 * ​​1012 *

Кто-нибудь знает, ктосделать это?

1 Ответ

0 голосов
/ 28 сентября 2019
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]}')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...