gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:26:16 24 4
gpt4 key购买 nike

作业代码有问题。基本上我想做的是接收一个对象列表并将它们传递给我的 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)

每当我调用 fire 方法并传入对象时,它都会指向第 17 行,即 x,y = targets[i].position 行并显示“TypeError: list indices must be整数,而不是轰炸机”

Bomber 是类的名称。我这样调用 fire 方法:

bOne.fire([bTwo, tOne, tTwo, tThree])

非常感谢任何帮助。

最佳答案

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

>>> for elem in ['a', 'b', 'c']:
... print elem
'a'
'b'
'c'

在 python 中,for 结构不仅仅适用于数字,它直接适用于您正在循环的序列的元素。

关于python - 列表索引必须是整数,而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12270663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com