Python字典列表实现电视节目排序时无法移除季数前导零问题
问题根因
代码读取季数时直接将带前导零的字符串存为字典键,全程未做数值转换,前导零会被完整保留;同时字符串类型的季数排序存在逻辑缺陷,比如字符串比较规则下"10"会排在"2"前面,不符合数值排序预期。
修正点
只需要调整核心逻辑即可解决问题:
- 读取季数键时,将字符串转为整数类型,Python会自动丢弃数字开头的前导零,同时后续排序会按数值大小正常执行
- 输出拼接内容时,将整数类型的季数转回字符串即可
- 额外增加空行跳过逻辑,避免文件首尾/中间存在空行时运行报错
- 改用
with语法读写文件,避免文件句柄泄漏问题
修正后可运行代码
# Trial 47... file_name = input() with open(file_name) as user_file: input_list = user_file.readlines() my_diction = {} for index in range(len(input_list)): line_content = input_list[index].strip('\n') if not line_content: continue if index % 2 == 0: # 季数字符串转整数,自动移除前导零 diction_key = int(line_content) if diction_key not in my_diction: my_diction[diction_key] = [] else: my_diction[diction_key].append(line_content) sorted_keys = sorted(my_diction.keys()) output_file = '' tv_show_list = [] for d_key in sorted_keys: output_file += str(d_key) + ': ' for tvshow in my_diction[d_key]: output_file += tvshow + '; ' tv_show_list.append(tvshow) output_file = output_file[:-2] + '\n' print(output_file) with open("output_keys.txt", "w") as f: f.write(output_file) tv_show_list.sort() sorted_list = '' for tv_show in tv_show_list: sorted_list += tv_show + '\n' print(sorted_list) with open("output_titles.txt", "w") as f: f.write(sorted_list)
运行效果
输入季数为"07"/"08"时,转整数后得到7/8,输出时自动转为无前置零的字符串,10及以上的多位季数不受影响,排序结果完全符合预期。
内容的提问来源于stack exchange,提问作者PDSK
相关产品推荐
相关产品推荐

