【问题标题】:Deleting list item in loop循环删除列表项
【发布时间】:2013-02-01 17:07:00
【问题描述】:

我目前正在尝试使用 pygame 开发游戏,但我的一些列表存在一些问题。真的很简单,我希望镜头在屏幕外时被删除。我当前的代码可以完美运行,直到我拍摄不止一个。

当前代码:

#ManageShots
for i in range (len(ShotArray)):
    ShotArray[i].x += 10
    windowSurface.blit(ShotImage, ShotArray[i])
    if(ShotArray[i].x > WINDOWWIDTH):
        ShotArray.pop(i)

错误信息:

ShotArray[i].x += 10
IndexError: list index out of range

【问题讨论】:

    标签: python list loops pygame


    【解决方案1】:

    从列表中弹出一个项目会将之后该项目的所有内容移到一个位置。因此,您最终会得到一个很容易超出范围的索引 i

    在循环后从列表中删除项目,或反向循环列表:

    for shot in reversed(ShotArray):
        shot.x += 10
        windowSurface.blit(ShotImage, shot)
        if shot.x > WINDOWWIDTH:
            ShotArray.remove(shot)
    

    【讨论】:

      【解决方案2】:

      问题是len(SortArray) 在循环开始时被评估一次。但是,您可以通过调用 ShotArray.pop(i) 来更改列表的长度。

      i = 0
      while i < len(ShotArray):
          ShotArray[i].x += 10
          windowSurface.blit(ShotImage, ShotArray[i])
          if(ShotArray[i].x > WINDOWWIDTH):
              ShotArray.pop(i)
          else:
              i += 1
      

      【讨论】:

      • 是的,我也在想同样的事情,但我确实认为我可以使用其他一些删除选项(如 pop)使其工作 我正在使用的代码是你看到的 ActionScript,并且他们在那里做的很像我在这里尝试的。你给了我一些很好的见解,非常感谢!
      【解决方案3】:

      你可能想要这样的东西:

      # update stuff
      for shot in ShotArray:
          shot.x += 10
          windowSurface.blit(ShotImage, shot)
      
      # replace the ShotArray with a list of visible shots
      ShotArray[:] =  [shot for shot in ShotArray if shot.x < WINDOWWIDTH]
      

      不要更改您正在迭代的列表的长度,这会导致混乱。

      【讨论】:

      • 有什么理由不做ShotArray = [shot for shot in ShotArray if shot.x &lt; WINDOWWIDTH]
      • 迄今为止我得到的最复杂的答案,请多多帮助!
      猜你喜欢
      • 2017-04-17
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      相关资源
      最近更新 更多