如何获取CSV中各车队对应列的最小值并存入Python字典?
问题描述
我正在编写Python代码读取勒芒赛事的CSV文件,文件包含赛道分段时间等信息,同一车队有多条记录但时间不同。目前代码无法正确保存各车队的最快(最小)分段时间,反而保存了最后或错误的数值。
原代码
def csv_reader (): correct = False while (not correct): try: filename=input("FileName.csv: ") f=open(filename, "r") csv_list = f.readlines() correct = True except IOError: print("ERROR") f.close() return csv_list def csv_data (csv_list): dictionary_1={} for line in csv_list: data=line.split(';') team=data[0] S1=(data[26]) if team in dictionary_1: if dictionary_1[team][0]>S1: dictionary_1[team][0]=S1 else: dictionary_1[team]=[0] dictionary_1[team][0]=S1 return dictionary_1 csv_list = csv_reader() del csv_list[0] print (csv_data(csv_list))
问题原因
- 字符串而非数值比较:代码直接用字符串格式的时间做比较,字符串是按ASCII码顺序判断大小,和实际时间数值逻辑不符(比如
"10.2"会被认为比"9.5"小)。 - 数据未清理:读取的行末尾带换行符,拆分后
S1可能包含\n,导致格式错误。 - 初始值冗余且类型冲突:新车队先设
[0]再替换成字符串时间,整数和字符串的后续比较会触发异常或错误逻辑。
修正后的代码
def csv_reader(): correct = False while not correct: try: filename = input("FileName.csv: ") with open(filename, "r") as f: csv_list = f.readlines() correct = True except IOError: print("ERROR") return csv_list def csv_data(csv_list): team_fastest_times = {} for line in csv_list: # 清理行尾换行符并拆分数据 data = line.strip().split(';') team = data[0].strip() try: # 转换为浮点数,确保数值比较逻辑正确 s1_time = float(data[26]) except ValueError: # 跳过无效时间数据 continue if team in team_fastest_times: if s1_time < team_fastest_times[team]: team_fastest_times[team] = s1_time else: team_fastest_times[team] = s1_time return team_fastest_times csv_list = csv_reader() del csv_list[0] print(csv_data(csv_list))
关键修正点
- 用
with语句管理文件,自动关闭文件避免资源泄漏。 - 用
strip()清理行尾换行符和车队名前后空格,保证数据干净。 - 将分段时间转为
float类型,基于数值比较找到真正的最小值。 - 添加异常处理,跳过无法转换为数值的无效数据行。
- 简化字典结构为
{车队名: 最快时间}的键值对,逻辑更直观。
内容的提问来源于stack exchange,提问作者SOLO180
相关产品推荐
相关产品推荐

