类型错误:列表索引必须是整数,而不是浮点数

新手上路,请多包涵

我有一个产生错误的 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

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

原文由 Dahaka 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 490
2 个回答

看起来您正在使用 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 中的楼层划分。

原文由 RocketDonkey 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

无论如何,RocketDonkey 的回答都完美地解释了为什么会出现错误。

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

 position = binary_search(names, entered)

正如雨果·费雷拉所说。

还要检查这个问题: ’/’ 和 ‘//’ 用于除法时有什么区别?

原文由 Nikos Tavoularis 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进