For循环到While循环在For While循环中使用

2024-04-19 18:34:57 发布

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

我对Python2.7还很陌生,所以我有几个关于使用for循环到while循环的问题。你知道吗

例如:我正在写这个定义

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

    for m in hazardflr:
        safetiles.append((m,step))
        i = 0
        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)

我正在尝试将所有for循环转换为while循环,所以这是我目前为止所写的内容。实际上,我不知道我们说的“While e in”是否在代码中间起作用。但是使用while循环规则,这段代码会和for循环一样吗?你知道吗

safezone = []
hazardflr = givenSteps(roomwidth,step,True)
safetiles = []
m=0
while m < hazardflr:
    safetiles.append((m,step))
    i = 0
    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])
                    e=0
                while 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]))
                    e+=1        
        i += 1
    m+=1
return sorted(safezone)

谢谢你的建议和帮助!你知道吗


Tags: intrueforifstepappendwhileroomwidth
3条回答

不,你的代码不一样

虽然它们看起来很相似,for item in listwhile item in list会做一些非常不同的事情。你知道吗

  • for item in list是一种对列表中的每一项都表示-do something with is的语法方式。你知道吗
  • while item in list是不同的-只要条件为真,while循环就会迭代。这种情况下的条件是item in list。它不会在每次迭代中更新项目,如果您从不更改itemlist的内容,它可能永远不会终止。此外,如果任何给定项不在列表中,它可能会提前终止。你知道吗

如果您想遍历一个列表并保持计数,那么使用while是错误的方法。改用^{}函数。

enumerate()获取一个列表,并返回一个元组列表,列表中的每一项按其索引的顺序排列,如下所示:

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

这个小小的变化意味着你不再需要手动跟踪你的指数。你知道吗

如果在Python中迭代列表中的每个项-使用for这就是它的设计目的。你知道吗

while aList:
     m= hazardflr.pop()
    # ...

应该大致等同于你的另一个循环

它完全取决于givenSteps返回的内容,但一般来说,没有for x in foofoo求值一次,然后依次将x指定为foo的每个元素。^另一方面,{}在每次迭代中计算foo,如果foo不是连续序列,则会提前结束。例如,如果foo = [0, 1, 2, 5, 6]for将使用foo的每个值,但是while将在2之后结束,因为3不在foo。^如果foo包含任何非整数值或低于起始值的数值,则{}也将不同于for。你知道吗

相关问题 更多 >