【问题标题】:python - TypeError: tuple indices must be integerspython - TypeError:元组索引必须是整数
【发布时间】:2012-03-23 03:54:10
【问题描述】:

我不明白有什么问题。我将发布相关的代码部分。

错误:

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]]

【问题讨论】:

    标签: python integer tuples pygame indices


    【解决方案1】:

    给定portal的初始化,循环

    for i in portal:
        ...
    

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        在 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] 在循环的第一次迭代中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-02-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-23
          • 1970-01-01
          • 2017-02-11
          相关资源
          最近更新 更多