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

Python按条件追加字符串:如何匹配禁用列表中所有元素

解决禁用前缀匹配所有元素的问题

你已经找对了方向,只差一步就能实现匹配所有禁用前缀的逻辑了,咱们来一步步修正:

问题根源

你之前写的if disregard[0] not in each:有两个明显的问题:

  1. 只检查了禁用列表里的第一个元素("http"),完全没处理第二个元素("gen");
  2. in操作是判断字符串包含该前缀,而不是以它开头——比如如果有个字符串是"xxxhttpxxx",也会被误过滤,这显然不是你想要的效果。

正确的判断逻辑

我们可以用str.startswith()方法结合any()函数来实现需求:

  • each.startswith(prefix):检查当前字符串是否以某个禁用前缀开头;
  • any(...):只要有一个前缀匹配就返回True,前面加not就表示没有任何一个禁用前缀匹配。

所以完整的判断条件应该是:

if len(each) == 40 and not any(each.startswith(prefix) for prefix in disregard):

修正后的完整代码

把原来的判断部分替换成上面的条件,最终代码如下:

import glob

words = []
store1 = []
disregard = ["http", "gen"]

for file_path in glob.glob(r'MYDIR'):
    with open(file_path, "r", encoding="utf-16") as f:
        text = f.read()
        lines = text.split("\n")
        for line in lines:
            words += line.split()

for each in words:
    if len(each) == 40 and not any(each.startswith(prefix) for prefix in disregard):
        store1.append(each)

测试你的示例输入

用你提供的测试文本:

http://1234ashajkhdajkhdajkhdjkaaaaaaad1
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
genp://1234ashajkhdajkhdajkhdjkaaaaaaad1
a\a
  • 第一行:长度远大于40,直接被过滤;
  • 第二行:长度正好40,且不以"http"或"gen"开头,会被加入store1;
  • 第三行:以"gen"开头,即使长度符合也会被过滤;
  • 第四行:长度不足40,被过滤。
    完全符合你的预期结果!

可选优化(如需不区分大小写)

如果你的输入里可能出现大写前缀(比如"HTTP"或"GEN"),可以把字符串和前缀都转成小写再判断:

if len(each) == 40 and not any(each.lower().startswith(prefix.lower()) for prefix in disregard):

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:38:32