Rem*_*ber 12 python dictionary pygame list
每次运行此程序时,都会收到此错误:
ValueError: list.remove(x): x not in list
我试图降低一个外星人的生命值,只要它被一个螺栓击中.如果这个外星人的健康状况也应该被摧毁<= 0.同样,螺栓也会被摧毁.这是我的代码:
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).只是为了澄清,字典aliens和bolts列表都是.
我究竟做错了什么?
Mar*_*ers 21
您不应该从正在循环的列表中删除项目.改为创建副本:
for a in aliens[:]:
和
for b in bolts[:]:
循环修改列表会影响循环:
>>> lst = [1, 2, 3]
>>> for i in lst:
...     print i
...     lst.remove(i)
... 
1
3
>>> lst
[2]
从循环两次的列表中删除项目会使事情变得更复杂,导致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
创建要在循环的每个级别修改的列表的副本时,可以避免此问题:
>>> 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螺栓,而不是在你伤害外星人的环路中.稍后分别清理外星人:
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
| 归档时间: | 
 | 
| 查看次数: | 53700 次 | 
| 最近记录: |