You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python代码调整最快人员统计结果的输出格式?

问题描述

我编写了一段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]的格式。我试过格式化打印的方法,但想要更优雅的实现方式,请问该如何修改代码?

修改方案

直接调整函数的返回值结构,把原有的元组返回改为列表合并的形式:

修改函数的最后一行返回语句,将fastest_person列表和四舍五入后的时间值合并成一个新列表返回即可。

修改后的完整代码:

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],完全符合格式要求。

如果后续出现多个平均时间相同的最快人员,该代码会自动返回['姓名1', '姓名2', 平均时间]的格式,保持了结果逻辑的一致性。

内容的提问来源于stack exchange,提问作者Red

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 18:15:24