我对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循环,所以这是我目前所写的。实际上,我不知道我们说的“we 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)谢谢你的建议或帮助!
发布于 2014-07-11 03:35:07
while aList:
m= hazardflr.pop()
# ...应该与您的另一个循环大致相同。
发布于 2014-07-11 03:33:43
不,你的代码不一样。
虽然它们看起来很相似,但for item in list和while item in list会做与截然不同的事情--。
for item in list是一种对列表中的每一项进行语法表达的方法--使用is来做一些事情。while item in list是不同的--只要条件为真,while循环就会迭代。本例中的条件是item in list。它不会每次迭代更新项目,如果您从不更改item或list是什么,它可能永远不会终止。此外,如果列表中没有任何给定项,则它可能过早终止。如果您想迭代一个列表并进行计数,那么使用while 是错误的。使用 enumerate() 函数代替.
enumerate()获取一个列表,并返回一个元组列表,列表中的每一项与其索引顺序一致,如下所示:
for i,m in enumerate(hazardflr):
safetiles.append((m,step))这一小变化意味着您不再需要手动跟踪索引。
如果您在Python-中迭代列表中的每一项,请使用,这是它设计的目的。
发布于 2014-07-11 03:34:17
这完全取决于givenSteps返回的内容,但通常情况下,不会。for x in foo对foo进行一次评估,然后依次将x指定为foo的每个元素。另一方面,while x in foo: ... x += 1在每次迭代中都会对foo进行评估,如果foo不是一个连续序列,它将提前结束。例如,如果是foo = [0, 1, 2, 5, 6],for将使用foo的每个值,但是while将在2之后结束,因为3不在foo中。如果while包含任何非整数值或低于起始值的值,则foo也将与for不同。
https://stackoverflow.com/questions/24689582
复制相似问题