【问题标题】:Changing for loop to while loop [duplicate]将for循环更改为while循环[重复]
【发布时间】:2019-03-19 01:07:57
【问题描述】:

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

【问题讨论】:

  • 输入和预期输出是什么?
  • for 循环看起来正确。为什么要改变它?
  • for 循环是正确的。任务是将其切换到 while 循环,但我遇到了属性错误。
  • 好吧,shapeList.append(shape) 只是将shape(始终为[])附加到shapeList,而您在一个空列表(即[])上调用move(dx,dy) .这就是你得到这个错误的原因。
  • 你应该做的是反复从shapeList中取出一个元素,并调用move(dx,dy),直到你访问了shapeList中的每个元素。

标签: python loops for-loop while-loop


【解决方案1】:

在你的代码的while循环版本中,shape变量被初始化为一个列表,所以它自然没有move方法。要将您的 for 循环转换为基本上是关于迭代形状对象列表的 while 循环,您可以将列表转换为 collections.deque 对象,以便您可以有效地将形状对象队列出列,直到它为空:

from collections import deque
def moveAll(shapeList, dx, dy):
    queue = deque(shapeList)
    while queue:
        shape = queue.popleft()
        shape.move(dx, dy)

【讨论】:

  • 这很好用,我确实认为还有其他方法,但谢谢。
【解决方案2】:

也许是这样的?

def moveAll(shapeList, dx, dy):
    while shapeList:
        shape = shapeList.pop(0)
        shape.move(dx, dy)

只要列表有项目,我们就删除一个并处理它。

不过,for 循环可能更有效,也更惯用。

【讨论】:

  • 请注意,这会改变传入列表,这可能不是人们所期望的(OP 的 for 循环不会改变它)。
  • 真;一个简单的解决方法是将shapeList[:] 复制到另一个变量,然后将pop 从该变量复制。
【解决方案3】:

奇怪的问题,奇怪的答案呵呵

def moveAll(shapeList, dx, dy): 
    try:
        ilist = iter(shapeList)
        while True:
            shape = next(ilist)
            shape.move(dx, dy)
    except:
        pass # done

【讨论】:

  • 如果move 返回的不是真实值(例如None,这很有可能),这将失败。
  • 你说得对哈哈。关于如何处理的任何想法?
  • 你需要单独存储next()的结果,然后调用move就可以了。为此,您可能需要一个 while True 循环。
  • 啊!好吧…………
猜你喜欢
  • 2018-08-13
  • 2017-09-26
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
  • 2020-09-17
  • 2022-01-19
  • 2014-04-05
  • 2021-11-23
相关资源
最近更新 更多