将 for 循环更改为 while 循环

这是我需要转换为 while 循环的 for 循环。我认为这会起作用,但它给了我一个没有移动属性的错误。这是一个创建人脸图形图像的程序,因此“shapeList”中的所有“形状”都是头部、鼻子、嘴巴、眼睛。面部需要沿着窗口的边缘移动。


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)


富国沪深
浏览 308回答 3
3回答

蛊毒传说

也许是这样的?def moveAll(shapeList, dx, dy):    while shapeList:        shape = shapeList.pop(0)        shape.move(dx, dy)只要列表中有项目,我们就会删除一个并处理它。不过,这个for循环可能更高效也更惯用。

胡说叔叔

奇怪的问题,奇怪的答案嘿嘿def moveAll(shapeList, dx, dy):     try:        ilist = iter(shapeList)        while True:            shape = next(ilist)            shape.move(dx, dy)    except:        pass # done

米脂

在while你的代码的循环版本中,shape变量被初始化为一个列表,所以它自然没有move方法。要将您的for循环转换为while基本上是关于迭代形状对象列表的循环,您可以将列表转换为collections.deque对象,以便您可以有效地将形状对象队列出列,直到它为空:from collections import dequedef moveAll(shapeList, dx, dy):    queue = deque(shapeList)    while queue:        shape = queue.popleft()        shape.move(dx, dy)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python