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

如何关联拆分后的弹珠ID与时间列表,找出最快弹珠及计算时间统计值

解决方案:关联弹珠ID与时间,找出最快弹珠

核心思路是将拆分后的弹珠编号与时间重新绑定,有两种简洁的实现方式:


方法一:利用列表索引关联(基于现有代码修改)

借助两个列表的索引对应关系,找到最短时间对应的弹珠ID:

def minute_converter(x):
    total_sec = int(x) if isinstance(x, float) else int(x)
    sec = total_sec % 60
    minutes = total_sec // 60
    print(f"{minutes} mins {sec} secs.")


def average(x):
    avg = [int(n) for n in x]
    return sum(avg) / len(avg)


print('Marble Racer Program')

data = ['331;;591', '010;;902', '809;;030', '756;;201', '128;;382']
marble_number = [x.split(';;', 1)[0] for x in data]
marble_times = [x.split(';;', 1)[1] for x in data]
print(marble_number)
print(marble_times)

# 找到最短/最长时间对应的弹珠ID
min_time = min(marble_times)
best_marble_id = marble_number[marble_times.index(min_time)]

max_time = max(marble_times)
worst_marble_id = marble_number[marble_times.index(max_time)]

# 输出结果
print(f'Marble with best time is {best_marble_id}: ', end='')
minute_converter(min_time)
print(f'Average time: ', end='')
minute_converter(average(marble_times))
print(f'Marble with worst time is {worst_marble_id}: ', end='')
minute_converter(max_time)
print(f'We have seen a total of {len(marble_number)} marbles.')

输出:

Marble Racer Program
['331', '010', '809', '756', '128']
['591', '902', '030', '201', '382']
Marble with best time is 809: 0 mins 30 secs.
Average time: 7 mins 1 secs.
Marble with worst time is 010: 15 mins 2 secs.
We have seen a total of 5 marbles.

方法二:整合为元组列表(更推荐)

直接将弹珠ID与转换为整数的时间配对,避免字符串比较的潜在错误(比如时间'99'和'100',字符串比较会误判'100'更小):

def minute_converter(total_sec):
    sec = int(total_sec) % 60
    minutes = int(total_sec) // 60
    print(f"{minutes} mins {sec} secs.")


def average(times):
    return sum(times) / len(times)


print('Marble Racer Program')

data = ['331;;591', '010;;902', '809;;030', '756;;201', '128;;382']
# 转换为(弹珠ID, 时间秒数)的元组列表
marble_data = [(item.split(';;')[0], int(item.split(';;')[1])) for item in data]
print([item[0] for item in marble_data])
print([str(item[1]) for item in marble_data])

# 找出最快/最慢弹珠
best_marble = min(marble_data, key=lambda x: x[1])
worst_marble = max(marble_data, key=lambda x: x[1])
avg_time = average([item[1] for item in marble_data])

# 输出结果
print(f'Marble with best time is {best_marble[0]}: ', end='')
minute_converter(best_marble[1])
print(f'Average time: ', end='')
minute_converter(avg_time)
print(f'Marble with worst time is {worst_marble[0]}: ', end='')
minute_converter(worst_marble[1])
print(f'We have seen a total of {len(marble_data)} marbles.')

这种方式的优势是数据结构更清晰,直接绑定ID与时间,无需维护两个独立列表,同时避免了字符串时间比较的风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:25:06