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

时间:2013-09-21 22:44:52

标签: python python-2.7

我的代码看起来像这样解析列表中的关键字吐出它们的位置,然后将其赋予弧,用计算代码替换位置,从而删除某些深度级别。 它实际上有效,但我现在要增加2或3个更深层次的水平,我正在寻找更优雅,更强大的东西,并且可以处理不定级别的深度。

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

sb.append(... ['mul', - 0.20,'hpt'] ...)

该列表适用于游戏,每个列表都是一个可以改变目标统计数据的咒语。我尝试编写语法来设计尽可能详细的法术,所以我想添加一个if条件,也许后来的其他基本操作:

“sb.append(......如果'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

0 个答案:

没有答案
相关问题