使用枚举或其他函数时的循环效率

时间:2014-07-11 05:02:37

标签: python if-statement for-loop while-loop enumeration

有人建议更换我的:

for m in hazardflr:
    safetiles.append((m, step))
    i = 0

采用更合理的方法,例如:

for i, m in enumerate(hazardflr):
    safetiles.append((m, step))

如果有办法提高效率,

我现在看到这如何节省代码行并说同样的事情。我不了解enum()功能。我现在的问题是,我是否可以做任何其他修改来使这段代码更有效率和节省线路?

def missingDoor(trapdoor, roomwidth, roomheight, step):        
    safezone = []
    hazardflr = givenSteps(roomwidth, step, True)
    safetiles = []

    for i, m in enumerate(hazardflr):
        safetiles.append((m,step))
        while i < len(safetiles):
            nextSafe = safetiles[i]
            if knownSafe(roomwidth, roomheight, nextSafe[0], nextSafe[1]):
                if trapdoor[nextSafe[0]/roomwidth][nextSafe[0]%roomwidth] is "0":
                    if nextSafe[0] not in safezone:
                        safezone.append(nextSafe[0])
                    for e in givenSteps(roomwidth, nextSafe[0], True):
                        if knownSafe(roomwidth, roomheight, e, nextSafe[0]):
                            if trapdoor[e/roomwidth][e%roomwidth] is "0" and (e,nextSafe[0]) not in safetiles:
                                safetiles.append((e,nextSafe[0]))
            i += 1  
    return sorted(safezone)

1 个答案:

答案 0 :(得分:0)

nextSafe[0]分配给本地变量

使用表达式nextSafe[0],您的代码是9次(如果我算的正确)。

从列表中访问项目比从变量中选择值更为昂贵。

修改如下:

for i,m in enumerate(hazardflr):
safetiles.append((m,step))
    while i < len(safetiles):
        nextSafe = safetiles[i]
        ns0 = nextSafe[0]
        if knownSafe(roomwidth, roomheight, ns0, nextSafe[1]):
            if trapdoor[ns0/roomwidth][ns0 % roomwidth] is "0":
                if ns0 not in safezone:
                    safezone.append(ns0)
                for e in givenSteps(roomwidth,ns0,True):
                    if knownSafe(roomwidth, roomheight, e, ns0):
                        if trapdoor[e/roomwidth][e%roomwidth] is "0" and (e, ns0) not in safetiles:
                            safetiles.append((e, ns0))

可以加快速度。

safezone转为set

测试item in list_var正在扫描list_var作为列表的整个列表。

如果您将测试设置为item in set_var,则无论set_var变量的大小如何,它都会立即知道结果,因为set的哈希值类似于&#34;数据库索引&#34;查找。

在您的代码中将safezone = []更改为safezone = set()

事实上,您可以在您的情况下完全跳过会员资格测试:

if ns0 not in safezone:
    safezone.append(ns0)

可以变成:

safezone.add(ns0)

as set将负责保留唯一的项目。