在循环中删除列表项

Tob*_*ing 1 python loops pygame list

我目前正在尝试使用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)
Run Code Online (Sandbox Code Playgroud)

错误信息:

ShotArray[i].x += 10
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

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

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

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