【问题标题】:Python - Sort a list contain string and intergerPython - 对包含字符串和整数的列表进行排序
【发布时间】:2019-09-28 14:30:44
【问题描述】:

这是我的代码:


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

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

有人知道谁来做这个吗?

【问题讨论】:

  • 感谢您的帮助,我们将不胜感激!

标签: python-3.x sorting


【解决方案1】:
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]}')

【讨论】:

  • 非常感谢,感谢!
  • 它说期望两个值,但只有一个存在:
  • 对于这一行:“User, Score = row.split(‘:’)
猜你喜欢
  • 2022-01-11
  • 1970-01-01
  • 2021-08-12
  • 2014-06-21
  • 2016-01-23
  • 2013-06-25
  • 2021-02-22
  • 1970-01-01
相关资源
最近更新 更多