Python解析深度未知的嵌套列表

2024-10-01 05:05:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码看起来是这样的,它解析关键字列表,然后将其输出给arc,后者用计算的代码替换位置,从而删除一些深度级别。 它实际上是可行的,但我现在要增加2到3个层次的深度,我正在寻找更优雅,更健壮,可以处理无限深度的东西。在

编辑:我想在列表中进行操作,列表应该能够处理简单的代码,比如加号、减号,我还想添加一个if条件。在一个列表中应该是这样的:

在某人追加(…['mul',-0.20,'hpt']…)

列表对于游戏来说每个列表都是一个可以改变目标属性的咒语。我试图编写语言来设计尽可能详细的拼写,因此我想添加一个if条件,也许以后还会添加其他基本操作:

““某人追加(…如果'hp'>;'mp':['mul',-0.20,'hpt']…)(字符串在前面被转换成数字)

但是列表是在函数外部编写的,在声明变量之前编写,甚至可能导入,所以我更喜欢转义代码。在

def parseop(tmpsp):
    for y in range ( len (tmpsp) ):
        if type(tmpsp[y]) is list:
            for x in range ( len (tmpsp[y]) ):
                if type(tmpsp[y][x]) is list:
                    for z in range ( len (tmpsp[y][x]) ):                               
                        if type(tmpsp[y][x][z]) is list:
                            for t in range ( len (tmpsp[y][x][z]) ): 
                                if type(tmpsp[y][x][z][t]) is list:
                                    for e in range ( len (tmpsp[y][x][z][t]) ): 
                                        if arn(tmpsp[y][x][z][t][e]): tmpcn.append([y,x,z,t])
                                if arn(tmpsp[y][x][z][t]): tmpcn.append([y,x,z])
                        if arn(tmpsp[y][x][z]): tmpcn.append([y,x])
                if arn(tmpsp[y][x]): tmpcn.append([y])
    if len (tmpcn):
        tmpcn.reverse()
        for x in range ( len (tmpcn) ):
            dprint ((tmpcn, len (tmpcn[x])))
            if len (tmpcn[x]) ==4:   tmpsp[tmpcn[x][0]][tmpcn[x][1]][tmpcn[x][2]][tmpcn[x][3]] = arg(tmpsp[tmpcn[x][0]][tmpcn[x][1]][tmpcn[x][2]][tmpcn[x][3]])
            elif len (tmpcn[x]) ==3:   tmpsp[tmpcn[x][0]][tmpcn[x][1]][tmpcn[x][2]] = arg(tmpsp[tmpcn[x][0]][tmpcn[x][1]][tmpcn[x][2]])
            elif len (tmpcn[x]) ==2: tmpsp[tmpcn[x][0]][tmpcn[x][1]]              = arg(tmpsp[tmpcn[x][0]][tmpcn[x][1]])
            elif len (tmpcn[x]) ==1: tmpsp[tmpcn[x][0]] 

def arg(tmp):
    ddprint ('arg',tmp)
    if tmp[0] == 'mul': 
        del tmp[0]
        for d in range ( len (tmp) ): 
            if ifa(tmp[d]):
                tmp[d] = ifa(tmp[d])

        ddprint ((arg, tmp))
        tmp = m(*tmp)
        ddprint ((arg, tmp))
        return tmp
    elif tmp[0] == 'div': 
        del tmp[0]
        for d in range ( len (tmp) ): 
            if ifa(tmp[d]):
                tmp[d] = ifa(tmp[d])
        tmp = d(*tmp)
        ddprint ((arg, tmp))
        return tmp
    elif tmp[0] == 'add': 
        del tmp[0]
        for d in range ( len (tmp) ): 
            if ifa(tmp[d]):
                tmp[d] = ifa(tmp[d])
        ddprint('add',tmp)
        tmp = a(*tmp)
        ddprint ((arg, tmp))
        return tmp
    else: print 'There is trouble in arg'

def arn(tmp):
    ddprint ('arn',tmp)
    if tmp == 'mul': return 1
    if tmp == 'div': return 1
    if tmp == 'add': return 1

Tags: in列表forlenreturnifisarg