Python 2.7给出了ValueError list.remove(x)x不在列表中 [英] Python 2.7 gives ValueError list.remove(x) x not in list

查看:5259
本文介绍了Python 2.7给出了ValueError list.remove(x)x不在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次运行此程序时,我都会收到以下错误:

Every time I run this program, I get this error:

ValueError list.remove(x)x不在列表中

我试图降低一个外星人的健康,当它被一个螺栓击中。如果外星人的健康状况为= 0,外星人也应该被摧毁。同样地,螺栓也会被破坏。这是我的代码:

I am trying to lower the health of an alien whenever it is hit by a bolt. The alien should also be destroyed if its health is <= 0. Similarly, the bolt would also be destroyed. Here is my code:

def manage_collide(bolts, aliens):
    # Check if a bolt collides with any alien(s)
    for b in bolts:
        for a in aliens:
            if b['rect'].colliderect(a['rect']):
                for a in aliens:
                    a['health'] -= 1
                    bolts.remove(b)
                    if a['health'] == 0:
                        aliens.remove(a)
    # Return bolts, aliens dictionaries
    return bolts, aliens

ValueError出现在行 aliens.remove(a)。只是为了澄清,外星人螺栓都是字典列表。

The ValueError appears on the line aliens.remove(a). Just to clarify, both the aliens and bolts are lists of dictionaries.

推荐答案

您不应该从正在循环的列表中删除项目。创建副本:

You should not remove items from a list you are looping over. Create a copy instead:

for a in aliens[:]:

for b in bolts[:]:

在循环时修改列表会影响循环:

Modifying a list while looping over it, affects the loop:

>>> lst = [1, 2, 3]
>>> for i in lst:
...     print i
...     lst.remove(i)
... 
1
3
>>> lst
[2]

从循环两次的列表中删除项目,使事情成为一个稍微复杂一点,导致ValueError:

Removing items from a list you are looping over twice makes things a little more complicated still, resulting in a ValueError:

>>> lst = [1, 2, 3]
>>> for i in lst:
...     for a in lst:
...         print i, a, lst
...         lst.remove(i)
... 
1 1 [1, 2, 3]
1 3 [2, 3]
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
ValueError: list.remove(x): x not in list

创建副本时您正在每个级别的循环中修改的列表,您可以避免此问题:

When creating a copy of the lists you are modifying at each level of your loops, you avoid the problem:

>>> lst = [1, 2, 3]
>>> for i in lst[:]:
...     for i in lst[:]:
...         print i, lst
...         lst.remove(i)
... 
1 [1, 2, 3]
2 [2, 3]
3 [3]

当您发生碰撞时,您只需删除 b bolt 一次,而不是在你伤害外星人的循环中。稍后清理外星人:

When you have a collision, you only need to remove the b bolt once, not in the loop where you hurt the aliens. Clean out the aliens separately later:

def manage_collide(bolts, aliens):
    for b in bolts[:]:
        for a in aliens:
            if b['rect'].colliderect(a['rect']) and a['health'] > 0:
                bolts.remove(b)
                for a in aliens:
                    a['health'] -= 1
    for a in aliens[:]:
        if a['health'] <= 0:
            aliens.remove(a)
    return bolts, aliens

这篇关于Python 2.7给出了ValueError list.remove(x)x不在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆