python-3.x - 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
有谁知道谁来做这个?
解决方案
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]}')
推荐阅读
- android - 无法使用 android 应用在 mesibo 中创建用户
- python - 无法将字典合并到列表中
- php - Laravel 5.8 追随者系统错误“无消息”
- exe - 在 Windows 可执行文件中调用 az storage blob upload 命令失败并出现奇怪的异常
- python - Pygame鼠标点击更新?
- mysql - MYSQL:触发器仅在第一次调用 SP
- ios - 视图控制器所需的便利性导致的 Swift 错误
- angularjs - 如何使用 AngularJS 设置开发环境?我无法启动和运行基本的 AngularJS 应用程序
- php - 无法从 URL 重写中获取值
- pandas - 来自 pyspark 的数据集的多处理返回 JVM 错误