Python - 类型错误:元组索引必须是整数

3
我不明白哪里有问题。我会发布相关代码部分。
错误:
Traceback (most recent call last):
  File "C:\Python\pygame\hygy.py", line 104, in <module>
    check_action()
  File "C:\Python\pygame\hygy.py", line 71, in check_action
    check_portal()
  File "C:\Python\pygame\hygy.py", line 75, in check_portal
    if [actor.x - 16, actor.y - 16] > portal[i][0] and [actor.x + 16, actor.y + 16] < portal[i][0]:
TypeError: tuple indices must be integers

功能:

def check_portal():
    for i in portal:
        if [actor.x - 16, actor.y - 16] > portal[i][0] and [actor.x + 16, actor.y + 16] < portal[i][0]:
            if in_portal == False:
                actor.x,actor.y=portal[i][1]
                in_portal = True
        elif [actor.x - 16, actor.y - 16] > portal[i][1] and [actor.x + 16, actor.y + 16] < portal[i][1]:
            if in_portal == False:
                actor.x,actor.y=portal[i][1]
                in_portal = True
        else:
            in_portal = False

初始化演员:

class xy:
  def __init__(self):
    self.x = 0
    self.y = 0
actor = xy()

初始化门户:

portal = [[100,100],[200,200]],[[300,300],[200,100]]
3个回答

1

假设已经初始化了portal,那么进入循环

for i in portal:
    ...

只会执行两次迭代。在第一次迭代中,i将是[[100,100],[200,200]]。尝试执行portal[i]将等同于portal[[[100,100],[200,200]]],这没有意义。您可能只想使用i而不是portal[i]。(您可能还想将其重命名为比i更有意义的名称。)


1

当你说for i in portal时,在每次迭代中,i实际上是portal的元素,而不是你可能想到的portal中的索引。因此,它不是整数,并导致portal[i][0]出错。

因此,一个快速修复方法就是将其替换为for i in xrange(len(portal)),其中i是索引。


0
在 for 循环中,i = ([100, 100], [200, 200]) 不是列表的有效索引。
根据 if 语句中的比较,看起来您的意图更像是:
for coords in portal:
   if [actor.x - 16, actor.y - 16] > coords[0] and [actor.x + 16, actor.y + 16] < coords[0]:

在循环的第一次迭代中,coords [0] == [100, 100]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接