类型错误:列表索引必须是整数,而不是浮
问题描述:
我有一个产生错误的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
我无法理解什么这个错误信息的意思。
答
它看起来像你使用Python 3.x. Python 3.x的一个重要区别是处理方式。当你做x/y
时,Python 2.x中返回一个整数,因为小数被截断(floor division)。但是,在3.x中,/
运算符执行“真”除法,导致产生float
而不是整数(例如1/2 = 0.5
)。这意味着你现在试图使用float来引用列表中的一个位置(例如my_list[0.5]
甚至my_list[1.0]
),这不会像Python期待的整数一样工作。因此,您可能首先要尝试使用middle = (first + last) // 2
,并进行调整,以便返回所期望的结果。 //
表示Python 3.x中的地板部分。
答
如何简单地重现上述错误:如果你打的是计算器,因为你得到这个错误
>>> stuffi = []
>>> stuffi.append("foobar")
>>> print(stuffi[0])
foobar
>>> stuffi[0] = "failwhale"
>>> print(stuffi[0])
failwhale
>>> stuffi[0.99857] = "skipper"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not float
。这意味着你没有阅读或理解错误信息。错误信息是完美的,它告诉你到底什么是错误的,它告诉你你犯了什么错误。
数组通过整数进行索引,您将一个非整数传入它,并且解释器告诉您不能这样做,因为它没有任何意义。
你需要重新审视教程:
"Python array tutorial"
"Python floats and primitive types tutorial"
你的变量需要转换为整数,然后才能将用于选择一个数组索引。
公案:
一名男子走进酒吧,和订单1.1195385啤酒,酒保翻了个白眼,说:TypeError: beer orders must be whole integers, not fractions.
答
我可能是错的,但此行:
binary_search(names, entered)
不会是
position = binary_search(names, entered)
请给予包含回溯的完整错误消息。 – BrenBarn