如何按列表元素首字符排序?Python文件排序代码调试求助
按行首整数排序文本文件的解决方案
问题分析
你的现有代码存在几个关键问题:
- 错误使用
split("-")分割行,实际文件内容用分号;分隔 - 处理时仅提取了每行的部分内容,未保留完整的编号与文本关联
- 排序函数仅打印首字符,未实现真正的排序逻辑
修正后的完整实现
核心思路
- 正确读取并拆分每行,将行首整数与对应文本绑定为元组
- 基于整数编号完成排序
- 可选转换为有序字典(Python 3.7+ 字典默认保持插入顺序)
from typing import List, Tuple def process_file(file_path: str) -> List[Tuple[int, str]]: items = [] with open(file_path, "r", encoding="utf-8") as file: for line in file: line = line.strip() if not line: continue # 跳过空行 # 按分号拆分,最多拆1次避免文本含分号的情况 parts = line.split(";", maxsplit=1) if len(parts) != 2: continue # 跳过格式错误的行 try: num = int(parts[0].strip()) text = parts[1].strip() items.append((num, text)) except ValueError: continue # 跳过编号非整数的行 return items def sort_by_number(items: List[Tuple[int, str]]) -> List[Tuple[int, str]]: # 按元组第一个元素(整数编号)升序排序 return sorted(items, key=lambda x: x[0]) def convert_to_ordered_dict(sorted_items: List[Tuple[int, str]]): # Python 3.7+ 字典默认保留插入顺序 return {str(num): text for num, text in sorted_items} # 执行流程 if __name__ == "__main__": raw_items = process_file("menu.txt") sorted_items = sort_by_number(raw_items) print("排序后的列表:") for num, text in sorted_items: print(f"{num};{text}") ordered_dict = convert_to_ordered_dict(sorted_items) print("\n排序后的字典:") print(ordered_dict)
代码说明
process_file:负责读取文件,拆分每行内容,将编号转为整数并与文本绑定,同时过滤无效行(空行、格式错误行)sort_by_number:利用Python内置sorted()函数,通过lambda表达式指定排序依据为元组的第一个元素(整数编号),实现升序排序convert_to_ordered_dict:将排序后的元组列表转换为字典,Python 3.7及以上版本的字典会自动保留排序后的顺序
测试结果
针对你的menu.txt内容:
4;Deleta 1;Insere 5;Mostra 3;Exclui 2;Altera
运行代码后输出:
排序后的列表: 1;Insere 2;Altera 3;Exclui 4;Deleta 5;Mostra 排序后的字典: {'1': 'Insere', '2': 'Altera', '3': 'Exclui', '4': 'Deleta', '5': 'Mostra'}
内容的提问来源于stack exchange,提问作者pedroo_
相关产品推荐
相关产品推荐

