TypeError:列表索引必须是整数,而不是浮点数 [英] TypeError: list indices must be integers, not float
问题描述
我有一个产生错误的python 3.x程序:
I have a python 3.x program that is producing an error:
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
我无法理解此错误消息的含义.
I am having trouble understanding what this error message means.
推荐答案
您似乎正在使用Python3.x. Python 3.x的重要区别之一是处理分割的方式.当您执行x / y
时,在Python 2.x中将返回一个整数,因为十进制会被截断(底数除法).但是在3.x中,/
运算符执行'true'除法,结果是float
而不是整数(例如1 / 2 = 0.5
).这意味着您现在正在尝试使用浮点数来引用列表中的位置(例如my_list[0.5]
甚至my_list[1.0]
),这将无法正常工作,因为Python需要一个整数.因此,您可能首先要尝试使用middle = (first + last) // 2
进行调整,以使结果返回您期望的结果. //
表示Python 3.x中的楼层划分.
It looks like you are using Python 3.x. One of the important differences in Python 3.x is the way division is handled. When you do x / y
, an integer is returned in Python 2.x because the decimal is truncated (floor division). However in 3.x, the /
operator performs 'true' division, resulting in a float
instead of an integer (e.g. 1 / 2 = 0.5
). What this means is that your are now trying to use a float to reference a position in a list (e.g. my_list[0.5]
or even my_list[1.0]
), which will not work as Python is expecting an integer. Therefore you may first want to try using middle = (first + last) // 2
, adjusting so that the result returns what you expect. The //
indicates floor division in Python 3.x.
这篇关于TypeError:列表索引必须是整数,而不是浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!