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

基于前缀标识筛选列表中结尾数字最小的文件名

筛选相同前缀对应结尾数字最小的文件名

我们可以通过分组前缀+跟踪最小数字的方式实现需求,具体步骤如下:

  • 拆分每个文件名的前缀(下划线分隔的前两部分)和结尾数字(下划线分隔的中间部分,去掉后缀)
  • 用字典存储每个前缀对应的最小数字文件名,遍历过程中更新最小值
  • 最后提取字典中的所有值得到结果

原文件列表

files = ['2022-04-27_Cc1a6yWpUeQ_2825282726106954381.jpg',
         '2022-04-27_Cc1a6yWpUeQ_2825282726106985382.jpg',
         '2022-04-27_Cc1cPL3punY_2825288523641594007.jpg',
         '2022-04-27_Cc1cPL3punY_2825288523641621697.jpg',
         '2022-04-27_Cc1cPL3punY_2825288523650051140.jpg',
         '2022-04-27_Cc1cPL3punY_2825288523650168421.jpg',
         '2022-04-27_Cc1cPL3punY_2825288523708854776.jpg',
         '2022-04-27_Cc1cPL3punY_2825288523717189707.jpg',
         '2022-04-27_Cc1dN3Rp0es_2825292832374568690.jpg',
         '2022-04-27_Cc1dN3Rp0es_2825292832383025904.jpg',
         '2022-04-27_Cc1dN3Rp0es_2825292832383101420.jpg',
         '2022-04-27_Cc1dN3Rp0es_2825292832383164193.jpg',
         '2022-04-27_Cc1dN3Rp0es_2825292832399945744.jpg',
         '2022-04-27_Cc1dN3Rp0es_2825292832458472617.jpg']

实现代码

prefix_min_files = {}

for file in files:
    # 拆分文件名:提取前缀、结尾数字
    parts = file.split('_')
    prefix = '_'.join(parts[:2])
    num = int(parts[2].split('.')[0])
    
    # 更新字典:保留当前前缀下数字最小的文件名
    if prefix not in prefix_min_files or num < int(prefix_min_files[prefix].split('_')[2].split('.')[0]):
        prefix_min_files[prefix] = file

# 生成结果列表
result = list(prefix_min_files.values())
print(result)

代码说明

  • 遍历每个文件名,通过字符串拆分操作分离出前缀和结尾数字(转为整数方便比较大小)
  • 字典prefix_min_files以前缀为键,存储对应前缀下数字最小的文件名,遍历过程中自动更新最小值
  • 最终字典的所有值就是我们需要的筛选结果

运行结果

['2022-04-27_Cc1a6yWpUeQ_2825282726106954381.jpg', 
 '2022-04-27_Cc1cPL3punY_2825288523641594007.jpg', 
 '2022-04-27_Cc1dN3Rp0es_2825292832374568690.jpg']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:36:28