在以下 Python 代码中(其中函数应该能够接收随机信息并返回平均时间最高的人的姓名和平均时间):
def the_fastest(times):
fastest_person = []
quickest_time = float('inf')
for person_data in times:
person_name = person_data[0]
person_times = person_data[1:]
total_time = sum(person_times)
avg_time = total_time / len(person_times)
if avg_time < quickest_time:
quickest_time = avg_time
fastest_person = [person_name]
elif avg_time == quickest_time:
fastest_person.append(person_name)
return fastest_person, round(quickest_time, 2)
#example times for testing
times = [['Jason', 11, 11, 11.2, 10.9], ['Wally', 11, 11.5], ['Sheri', 12, 25], ['Jimmy', 10.1, 10.8, 12.1], ['Tina', 10.15, 10.223, 10.185, 10.22], ['Carmen', 12.15, 12.2, 12.18, 12.33]]
print(the_fastest(times))
我的结果是返回正确的信息,但格式错误。我回来了:
(['Tina'], 10.19)
但我希望它的格式为:
['Tina', 10.19]
。
我尝试过用蛮力方法告诉
print(f"['{name}',{time}]")
,这很有效,但我想要更优雅的东西。
def the_fastest(times):
# fastest_person = [] # <-- fastest_person isn't a list, it's just one person
fastest_person = None
quickest_time = float('inf')
for person_data in times:
person_name = person_data[0]
person_times = person_data[1:]
total_time = sum(person_times)
avg_time = total_time / len(person_times)
if avg_time < quickest_time:
quickest_time = avg_time
# fastest_person = [person_name] # <-- don't use a list
fastest_person = person_name
elif avg_time == quickest_time:
fastest_person.append(person_name)
# return fastest_person, round(quickest_time, 2) # <-- this is where you create your return list
return [fastest_person, round(quickest_time, 2)]
#example times for testing
times = [['Jason', 11, 11, 11.2, 10.9], ['Wally', 11, 11.5], ['Sheri', 12, 25], ['Jimmy', 10.1, 10.8, 12.1], ['Tina', 10.15, 10.223, 10.185, 10.22], ['Carmen', 12.15, 12.2, 12.18, 12.33]]
print(the_fastest(times))