合并中的不可合并类型排序“int()< = list()”

时间:2014-08-25 20:28:13

标签: python

此合并排序实现在此错误上失败:“if(left_list [0]< = right_list [0]):TypeError:unorderable types:int()< = list()。”

为什么right_list [0]被认为是一个列表而不是一个int?

def merge_sort(array):

    def merge(left_list, right_list):

        result = []

        while len(left_list) > 0 or len(right_list) > 0:

            if len(left_list) > 0 and len(right_list) > 0:

                if (left_list[0] <= right_list[0]):

                    result.append(left_list[0])

                    left_list = left_list[1:]

                else:
                    result.append(right_list[0])

                    right_list = right_list[1:]



            elif len(left_list) > 0:

                result.append(left_list)
                left_list = left_list[1:]

            elif len(right_list) >  0:

                result.append(right_list[0])
                right_list = right_list[1:]

        return result

    if len(array) < 2:

        return array

    i_mid = len(array)//2

    left = array[:i_mid] 

    right = array[i_mid:]

    left = merge_sort(left)
    right = merge_sort(right) 

    result = merge(left, right)

    return result

1 个答案:

答案 0 :(得分:3)

错误:一个分支返回一个列表,当它应该是一个项目:)固定。

def merge_sort(array):
    def merge(left_list, right_list):
        result = []
        while len(left_list) > 0 or len(right_list) > 0:
            if len(left_list) > 0 and len(right_list) > 0:
                if (left_list[0] <= right_list[0]):
                    result.append(left_list[0])
                    left_list = left_list[1:]
                else:
                    result.append(right_list[0])
                    right_list = right_list[1:]
            elif len(left_list) > 0:
                result.append(left_list[0]) # <==
                left_list = left_list[1:]
            elif len(right_list) >  0:
                result.append(right_list[0])
                right_list = right_list[1:]
        return result

    if len(array) < 2:
        return array

    i_mid = len(array)//2
    left = array[:i_mid] 
    right = array[i_mid:]
    left = merge_sort(left)
    right = merge_sort(right) 
    result = merge(left, right)
    return result

print merge_sort([5,4,3,1,2])

输出

[1, 2, 3, 4, 5]