Python 将for循环更改为while循环
这是我需要转换为while循环的for循环。我原以为这会起作用,但它给了我一个错误,移动时没有属性。这是一个创建面部图形图像的程序,因此“shapeList”中的所有“形状”都是头部、鼻子、嘴巴和眼睛。该面需要沿窗口边缘移动Python 将for循环更改为while循环,python,loops,for-loop,while-loop,Python,Loops,For Loop,While Loop,这是我需要转换为while循环的for循环。我原以为这会起作用,但它给了我一个错误,移动时没有属性。这是一个创建面部图形图像的程序,因此“shapeList”中的所有“形状”都是头部、鼻子、嘴巴和眼睛。该面需要沿窗口边缘移动 def moveAll(shapeList, dx, dy): for shape in shapeList: shape.move(dx, dy) def moveAll(shapeList, dx, dy): shape
def moveAll(shapeList, dx, dy):
for shape in shapeList:
shape.move(dx, dy)
def moveAll(shapeList, dx, dy):
shape = []
while shape != shapeList:
shapeList.append(shape)
shape.move(dx, dy)
在代码的
while
循环版本中,shape
变量初始化为列表,因此它自然没有move
方法。要将for
循环转换为,而循环基本上是迭代形状对象列表,可以将列表转换为collections.deque
对象,以便有效地将形状对象队列出列,直到其为空:
from collections import deque
def moveAll(shapeList, dx, dy):
queue = deque(shapeList)
while queue:
shape = queue.popleft()
shape.move(dx, dy)
奇怪的问题,奇怪的回答呵呵
def moveAll(shapeList, dx, dy):
try:
ilist = iter(shapeList)
while True:
shape = next(ilist)
shape.move(dx, dy)
except:
pass # done
也许是这样的
def moveAll(shapeList, dx, dy):
while shapeList:
shape = shapeList.pop(0)
shape.move(dx, dy)
只要列表中有项目,我们就删除一个并处理它
不过,for
循环可能更有效,也更惯用。输入和预期输出是什么?for
循环看起来是正确的。为什么要更改它?for循环是正确的。任务是将其切换到while循环,我遇到了属性错误。嗯,shapeList.append(shape)
只是将shape
追加到shapeList
,而您正在空列表上调用move(dx,dy)
(即[]
)。这就是为什么会出现错误。您应该反复从shapeList
中获取一个元素,并调用move(dx,dy)
,直到您访问了shapeList
中的每个元素。如果move
返回的值不是真实值(例如None
,这可能会失败).你说得对,哈哈。你知道如何处理吗?你必须分别存储next()
的结果,然后调用move
。你可能需要一个while True
循环!好的………注意这会改变传入列表,这可能不是我们在这里所期望的(OP的for循环不会改变它);一个简单的解决方法是将shapeList[:]
复制到另一个变量,然后从中取而代之pop
。这很有效,我确实认为还有另一种方法,但谢谢您。