Python: list indices must be integers or slices, not float问题
今天尝试使用PyCharm来编写一个Python程序,结果报错
TypeError: list indices must be integers or slices, not float
出错代码
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) / 2] #报错 line4
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
print (quicksort([3, 6, 8, 10, 12, 13, 1, 2]))
这是一个简易的快排程序
经过查阅得到 “/”是浮点数除法,但是在此程序中需要整除,所以要用“%”或者“//”
所以经过更改后的Python代码
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) % 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
print (quicksort([3, 6, 8, 10, 12, 13, 1, 2]))
结果
[1, 2, 3, 6, 8, 10, 12, 13]
Process finished with exit code 0
成功输出