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

Python字符串处理代码异常:列表元素意外合并问题排查

问题:列表末尾元素被错误合并的Python代码调试

我的Python代码

a=open("example.nx",'r').read()
b=a.replace("\n","").replace("  ","").split("|")
for i in b: 
    if (len(i)==2 or len(i)==1) and i.__contains__("}") or i.__contains__(")"):
        """doesn't belong is probably a closing bracket"""
        index=b.index(i)
        b[index-1]=b[index-1]+b[index]#add the closing brackets to the one before deleting it
        del b[index]
    """check for brackets opened that aren't closed"""
    if (i.__contains__("(") and not i.__contains__(")")) or (i.__contains__("{") and not i.__contains__("}")):
        #these are not closed
        index=b.index(i)
        if b[index+1].__contains__(")") or b[index+1].__contains__("}"):
            #add them together then delete the extra
            b[index]=b[index]+b[index+1]
            del b[index+1] 
del b[len(b)-1]
print(b)

对应的example.nx文件内容

bp myClass(
    myClass[arg1]{
        set myArg to arg1|
    }
)|
def myFunction[arg2,arg3]{
    set a to arg2|
    set b to arg3|
}|
set var1 to 3|
set var2 to 4|
myFunction(var1,var2)|

实际输出结果

['bp myClass(myClass[arg1]{set myArg to arg1})', 'def myFunction[arg2,arg3]{set a to arg2', 'set b to arg3}', 'set var1 to 3', 'set var2 to 4myFunction(var1,var2)']

预期输出结果

['bp myClass(myClass[arg1]{set myArg to arg1})', 'def myFunction[arg2,arg3]{set a to arg2', 'set b to arg3}', 'set var1 to 3', 'set var2 to 4','myFunction(var1,var2)']

问题定位与分析

我定位到可能出问题的代码块:

if (len(i)==2 or len(i)==1) and i.__contains__("}") or i.__contains__(")"):
        """doesn't belong is probably a closing bracket"""
        index=b.index(i)
        b[index-1]=b[index-1]+b[index]#add the closing brackets to the one before deleting it
        del b[index]

原本以为只有长度为1或2且包含}或)的元素才会触发合并,但末尾的'set var2 to 4'和'myFunction(var1,var2)'明显不符合长度条件却被合并了,这是因为逻辑运算符优先级导致的条件判断错误:

Python中and的优先级高于or,所以原条件等价于:

((len(i)==2 or len(i)==1) and i.__contains__("}")) or i.__contains__(")")

也就是说,只要元素包含),不管它的长度是多少,都会触发合并逻辑。而'myFunction(var1,var2)'包含),所以循环到它时,会找到它的索引,将它和前一个元素'set var2 to 4'合并,这就导致了不符合预期的结果。

修复方案

给i.__contains__("}") or i.__contains__(")")加上括号,确保长度条件和括号判断是“且”的关系:

if (len(i)==2 or len(i)==1) and (i.__contains__("}") or i.__contains__(")")):
        """doesn't belong is probably a closing bracket"""
        index=b.index(i)
        b[index-1]=b[index-1]+b[index]#add the closing brackets to the one before deleting it
        del b[index]

修改后,只有长度为1或2并且包含}或)的元素才会触发合并逻辑,'myFunction(var1,var2)'长度远大于2,不会被处理,就能得到预期的输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:57:38