我对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)
谢谢你的建议和帮助!你知道吗
不,你的代码不一样
虽然它们看起来很相似,
for item in list
和while item in list
会做一些非常不同的事情。你知道吗for item in list
是一种对列表中的每一项都表示-do something with is的语法方式。你知道吗while item in list
是不同的-只要条件为真,while
循环就会迭代。这种情况下的条件是item in list
。它不会在每次迭代中更新项目,如果您从不更改item
或list
的内容,它可能永远不会终止。此外,如果任何给定项不在列表中,它可能会提前终止。你知道吗如果您想遍历一个列表并保持计数,那么使用} 函数。
while
是错误的方法。改用^{enumerate()
获取一个列表,并返回一个元组列表,列表中的每一项按其索引的顺序排列,如下所示:这个小小的变化意味着你不再需要手动跟踪你的指数。你知道吗
如果在Python中迭代列表中的每个项-使用
for
这就是它的设计目的。你知道吗应该大致等同于你的另一个循环
它完全取决于}在每次迭代中计算}也将不同于
givenSteps
返回的内容,但一般来说,没有for x in foo
对foo
求值一次,然后依次将x
指定为foo
的每个元素。^另一方面,{foo
,如果foo
不是连续序列,则会提前结束。例如,如果foo = [0, 1, 2, 5, 6]
,for
将使用foo
的每个值,但是while
将在2之后结束,因为3不在foo
。^如果foo
包含任何非整数值或低于起始值的数值,则{for
。你知道吗相关问题 更多 >
编程相关推荐