【问题标题】:TypeError: list indices must be integers, not floatTypeError:列表索引必须是整数,而不是浮点数
【发布时间】:2012-11-01 14:11:09
【问题描述】:

我有一个产生错误的 python 3.x 程序:

def main():
    names = ['Ava Fischer', 'Bob White', 'Chris Rich', 'Danielle Porter',
             'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle',
             'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']

    entered = input('Enter the name of whom you would you like to search for:')
    binary_search(names, entered)

    if position == -1:
        print("Sorry the name entered is not part of the list.")
    else:
        print(entered, " is part of the list and is number ", position, " on the list.")
    input('Press<enter>')

def binary_search(names, entered):
    first = 0
    last = len(names) - 1
    position = -1
    found = False

    while not found and first <= last:
        middle = (first + last) / 2

        if names[middle] == entered:
            found = True
            position = middle
        elif names[middle] > entered:
            last = middle - 1
        else:
            first = middle + 1

    return position

main()

错误是:

TypeError: list indices must be integers, not float

我无法理解此错误消息的含义。

【问题讨论】:

  • 请提供完整的错误信息,包括回溯。

标签: list python-3.x binary-search typeerror


【解决方案1】:

看起来您使用的是 Python 3.x。 Python 3.x 的重要区别之一是处理除法的方式。当您执行x / y 时,Python 2.x 中将返回一个整数,因为小数点被截断(地板除法)。但是在 3.x 中,/ 运算符执行“真”除法,结果是 float 而不是整数(例如 1 / 2 = 0.5)。这意味着您现在正在尝试使用浮点数来引用列表中的位置(例如my_list[0.5] 甚至my_list[1.0]),因为 Python 需要一个整数,所以这将不起作用。因此,您可能首先要尝试使用middle = (first + last) // 2,进行调整以使结果返回您所期望的。 // 表示 Python 3.x 中的楼层划分。

【讨论】:

    【解决方案2】:

    聚会有点晚了,但你也可以使用:

    middle = int((first + last) / 2)

    RocketDonkey 回答中完美地解释了您为什么会收到错误。

    为了让您的代码正常工作,您还应该设置:

    position = binary_search(names, entered)
    

    正如雨果·费雷拉所说。

    同时检查这个问题:What is the difference between '/' and '//' when used for division?

    【讨论】:

      【解决方案3】:

      我在函数 testOnData() 上使用 ANN 和 PyBrain 时遇到了这个问题。

      所以,我解决了这个问题,将“//”而不是“/”放在 backprop.py 源代码的索引中。

      我变了:

      print(('Max error:', 
          max(ponderatedErrors), 
          'Median error:',
           sorted(ponderatedErrors)[len(errors) / 2])) # <-- Error area 
      

      收件人:

      print(('Max error:', 
          max(ponderatedErrors), 
          'Median error:',
           sorted(ponderatedErrors)[len(errors) // 2])) # <-- SOLVED. Truncated
      

      希望对你有帮助。

      【讨论】:

        【解决方案4】:

        我可能是错的,但这一行:

        binary_search(names, entered)
        

        不会

        position = binary_search(names, entered)
        

        【讨论】:

          【解决方案5】:

          如果first = 0last = 6 然后使用/ 运算符,您将得到3.0,因此您的编译器会出错,因此您需要对其进行类型转换。

          middle = int((first + last) / 2)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-03-03
            • 2020-01-15
            • 1970-01-01
            • 1970-01-01
            • 2018-01-03
            • 1970-01-01
            • 2015-11-20
            • 1970-01-01
            相关资源
            最近更新 更多