列表索引必须是整数,而不是对象

use*_*246 2 python list

家庭作业的代码有问题.基本上我要做的就是接受一个对象列表并将它们传递给我的fire方法.

def fire(self,targets):
    i = 0
    for i in targets:
        x,y = targets[i].position
        tx,ty = self.position
        d = getDist(targets[i].position, self.position)
Run Code Online (Sandbox Code Playgroud)

每当我调用fire方法并传入对象时,它就会指向第17行,即x,y = targets[i].position行,并说"TypeError:list indices必须是整数,而不是Bomber"

轰炸机是班级的名称.我像这样调用fire方法:

bOne.fire([bTwo, tOne, tTwo, tThree])
Run Code Online (Sandbox Code Playgroud)

任何帮助深表感谢.

Mar*_*ers 8

您正在循环遍历列表本身,这意味着您不需要将值用作索引:

>>> for elem in ['a', 'b', 'c']:
...     print elem
'a'
'b'
'c'
Run Code Online (Sandbox Code Playgroud)

在python中,for构造不仅仅与数字一起工作,它直接与您循环的序列的元素一起工作.