python - TypeError:元组索引必须是整数

时间:2012-03-05 16:58:31

标签: python integer tuples pygame indices

我没有弄到什么问题。我将发布相关代码的一部分。

错误:

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 个答案:

答案 0 :(得分:1)

鉴于portal的初始化,循环

for i in portal:
    ...

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

答案 1 :(得分:1)

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

因此,快速解决方案只是将for i in xrange(len(portal))替换为i,而{{1}}就是索引。

答案 2 :(得分: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]

相关问题