Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将for循环更改为while循环_Python_Loops_For Loop_While Loop - Fatal编程技术网

Python 将for循环更改为while循环

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

这是我需要转换为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)

在代码的
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
。这很有效,我确实认为还有另一种方法,但谢谢您。