Python-竞赛结果-问题排序dictionay条目和打印出特定形式的数据



FYI我是python的新手,有一种更有效的方法可以产生所需的结果。请随时提出替代方法。

问题1-我想不出一种方法来添加"第一名:,第二名:等"到输出1

问题2-我不明白为什么在输出2中,我没有时间打印。

import os
os.system('cls')
#**********************************************
# The goal of this script is to collect both a racers name and finish time. When the last
# racers data is entered the script will order the names of racers (i.e. First, Second,
# Third) based on time (less time is better.) and print the ordered results to the screen.
# The race times will be entered as integers.
#**********************************************
# Sample input:
# What is the first racers name: Larry 
# What is the first racers time: 12
# What is the second racers name: Moe 
# What is the second racers time: 9
# What is the third racers name: Curly 
# What is the third racers time: 20

# Sample output:
# 1st Place: Moe
# 2nd Place: Larry
# 3rd Place: Curly
#**********************************************

print ('n')
print ('n')

# Enter the first racers name
racer_name_1 = input("Enter racer number one's name: ")

# Enter the first racers time 
racer_time_1 = int(input("Enter racer number one's time: "))

# Enter the Second racers name
racer_name_2 = input("Enter racer number two's name: ")

# Enter the Second racers time 
racer_time_2 = int(input("Enter racer number two's time: "))

# Enter the Third racers name
racer_name_3 = input("Enter racer number three's name: ")

# Enter the Third racers time 
racer_time_3 = int(input("Enter racer number three's time: "))

# Create the race results dictionary
raceList = {racer_name_1:"racer_time_1", racer_name_2:"racer_time_2", 
racer_name_3:"racer_time_3"}

print ('n')
# This is output 1
for value in sorted(raceList, reverse=True):
print (value)

print ('n')
# This is output 2
print (raceList)

print ('n')
print ('n')

问题2

这里不需要引号,否则这些值将被解释为字符串文字,它们是

raceList = {racer_name_1:"racer_time_1",
            racer_name_2:"racer_time_2", 
            racer_name_3:"racer_time_3"}

只需使用您的变量作为值

raceList = {racer_name_1: racer_time_1,
            racer_name_2: racer_time_2, 
            racer_name_3: racer_time_3}

问题1

制作一个元组列表,如(名称、时间)

racers = [(i, raceList[i]) for i in raceList]

按时间对列表进行排序

places = sorted(racers, key = lambda i: int(i[1]))

然后根据排序列表中的位置打印出他们的名字。

print('1st Place: {}'.format(places[0][0]))
print('2nd Place: {}'.format(places[1][0]))
print('3rd Place: {}'.format(places[2][0]))

最新更新