首页 > 编程语言 > 详细

Python: list indices must be integers or slices, not float问题

时间:2020-03-10 22:31:36      阅读:1207      评论:0      收藏:0      [点我收藏+]

今天尝试使用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

成功输出

Python: list indices must be integers or slices, not float问题

原文:https://www.cnblogs.com/hesenbai/p/12458791.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!