Python中如何保留同子串的v0版本及最高版本文件?
高效筛选版本文件的Python实现
需求说明
原始文件名列表:
[10998321023D123T][v0].jpg [10998321023D123T][v12321].jpg [10998321023D123T][v62221].jpg [10DFSA783212131T][v0].jpg [10DFSA783212131T][v32112].jpg [10DFSA783212131T][v54541].jpg
需要保留每个标识子串(比如10998321023D123T、10DFSA783212131T)对应的v0版本文件,以及该标识下的最高版本文件,移除其他非v0的低版本文件,最终结果:
[10998321023D123T][v0].jpg [10998321023D123T][v62221].jpg [10DFSA783212131T][v0].jpg [10DFSA783212131T][v54541].jpg
优化实现方案
不用为每个标识单独创建列表,而是用一个字典做分组存储,一次遍历即可完成处理,内存占用更低、效率更高:
import re def filter_version_files(filenames): # 正则匹配:提取标识子串和版本号数字 pattern = re.compile(r'\[(.*?)\]\[v(\d+)\]\.jpg') # 字典结构:key=标识子串,value=(v0文件名, 最高版本文件名, 当前最高版本号) file_groups = {} for filename in filenames: match = pattern.match(filename.strip()) if not match: continue # 跳过不符合格式的文件 identifier, version_str = match.groups() version = int(version_str) if identifier not in file_groups: # 首次遇到该标识,初始化 if version == 0: file_groups[identifier] = (filename, None, 0) else: file_groups[identifier] = (None, filename, version) else: current_v0, current_highest_file, current_highest_ver = file_groups[identifier] if version == 0: # 更新v0文件 file_groups[identifier] = (filename, current_highest_file, current_highest_ver) elif version > current_highest_ver: # 更新最高版本文件和版本号 file_groups[identifier] = (current_v0, filename, version) # 收集所有需要保留的文件:v0 + 最高版本(注意去重,避免v0同时是最高版本的情况) result = [] for v0_file, highest_file, _ in file_groups.values(): if v0_file: result.append(v0_file) if highest_file and highest_file != v0_file: result.append(highest_file) return result # 测试示例 original_files = [ "[10998321023D123T][v0].jpg", "[10998321023D123T][v12321].jpg", "[10998321023D123T][v62221].jpg", "[10DFSA783212131T][v0].jpg", "[10DFSA783212131T][v32112].jpg", "[10DFSA783212131T][v54541].jpg" ] filtered_files = filter_version_files(original_files) for f in filtered_files: print(f)
方案优势
- 仅需一次遍历所有文件,时间复杂度为O(n),n为文件总数
- 用字典存储分组信息,内存占用仅与不同标识的数量相关,远低于为每个标识创建列表的方案
- 自动处理边界情况:比如某个标识只有v0版本时,不会重复添加;版本号解析用正则保证准确性
内容的提问来源于stack exchange,提问作者Wamy-Dev
相关产品推荐
相关产品推荐

