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

文件列表多条件筛选疑问:结果异常原因及代码优化咨询

文件筛选问题解答

给定文件列表:

file_list = ['00AAAredneck20240213134024.csv',
             '00AAAredneck20240213134024.raw',
             '00AAAredneck20240213134024cal.csv',
             '01BBB_CC-PPP20240213134024_merged.csv',
             '01DEFG20240213134024.csv',
             '01DEFG20240213134024.raw',
             '01DE FG20240213134024.csv',
             '01DE FG20240213134024.raw',
             '01DEFG-PPP20240213x001.csv',
             '01DEFG-PPP20240213x002.csv',
             '01DEFG-PPP20240213x003.csv',
             '01DEFG-PPP20240213x004.csv',
             '01DEFG-PPP20240213x005.csv',
             '01DEFG-PPP20240213x006.csv',
             '01DEFG-RAW20240213x001.dat',
             '01DEFG-RAW20240213x002.dat',
             '01DEFG-RAW20240213x003.dat',
             '02HHHLLL20240213134024.csv',
             '02HHHLLL20240213134024.raw',
             '20240213134024Comb.csv',
             'PICsfile_1AAAredneck_20240213134024',
             'PICsindex_1AAAredneck_20240213134024',
             'Log20240213134024.txt',
             'O20240213134024.ini',
             'data.ini',
            ]

使用以下代码筛选:

search_file =[x for x in file_list if 'DE' in x and 'EF' in x and 'csv' in x and 'PPP' not in x]
print(search_file)

仅得到结果:

['01DEFG20240213134024.csv']

问题1:为何带空格的01DE FG20240213134024.csv未出现在结果列表中?

因为筛选条件里包含'EF' in x,而带空格的文件名中DE和FG之间有空格,不存在连续的EF字符串,因此不满足条件被排除。如果要匹配这两个文件,只需把'EF' in x替换为'FG' in x,确保文件名同时包含DE和FG即可。

问题2:有没有比'string1' in x and 'string2' in x and 'string3' not in x更简洁的方式来表达包含与排除条件?

有两种实用的简洁写法:

方法1:用列表结合all()函数

将需要包含的关键词、需要排除的关键词分别存入列表,通过all()批量判断,扩展性和可读性更强:

includes = ['DE', 'FG', 'csv']
excludes = ['PPP']
search_file = [x for x in file_list if all(k in x for k in includes) and all(k not in x for k in excludes)]

方法2:使用正则表达式

把所有条件整合到一个正则规则中,适合复杂匹配场景:

import re
search_file = [x for x in file_list if re.match(r'^(?!.*PPP).*DE.*FG.*\.csv$', x)]

该正则的含义:

  • ^(?!.*PPP):排除包含PPP的字符串
  • .*DE.*FG.*:确保字符串同时包含DE和FG(顺序固定)
  • \.csv$:确保文件以.csv结尾

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 15:17:15