【发布时间】:2014-07-11 03:23:47
【问题描述】:
我是 Python 2.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)
感谢您的任何建议或帮助!
【问题讨论】:
-
“我正在尝试将所有 for 循环转换为 while 循环”——为什么?
-
@MattDMo:实际上是这样;
in只是成员资格测试操作员。 -
@MattDMo
while e in ...有什么问题? -
@SteveZrg 通常在 Python 中,编码人员应该学习相反的方向,将无效的
while循环按索引访问项目以使用for循环。但是可能有像这里这样的原因,当迭代在处理过程中被修改时(参见safetiles.append((e, nextSafe[0]))无论如何,只有当你有充分的理由时,你才应该执行while循环。
标签: python python-2.7 if-statement for-loop while-loop