繁体   English   中英

精简版从python中的函数返回时为空

[英]Lite empty on return from function in python

问题是为什么变量测试为空? 程序将返回正确排序的数组。 但似乎没有得到分配。

def my_sort(array_to_sort):
    sort = False
    number_of_items = len(array_to_sort)
    print "sorted array: ", array_to_sort

    for i in range(0, number_of_items-1):
        if array_to_sort[i] > array_to_sort[i+1]:
            tmp = array_to_sort[i]
            array_to_sort[i] = array_to_sort[i+1]
            array_to_sort[i+1] = tmp
            sort = True
    if sort == True:
        my_sort(array_to_sort)
    elif sort == False:
        return array_to_sort

if __name__ == '__main__':
    # main()

    arr = [4,5,7,3,2,1]
    test = my_sort(arr)
    print (test)

这将返回以下内容。

sorted array:  [4, 5, 7, 3, 2, 1]
sorted array:  [4, 5, 3, 2, 1, 7]
sorted array:  [4, 3, 2, 1, 5, 7]
sorted array:  [3, 2, 1, 4, 5, 7]
sorted array:  [2, 1, 3, 4, 5, 7]
sorted array:  [1, 2, 3, 4, 5, 7]
None

您忘记了第一个条件的回报:

if sort == True:
    return my_sort(array_to_sort)

同样,您也不需要将布尔值与布尔值进行比较。 您的代码应如下所示:

def my_sort(array_to_sort):
    sort = False
    number_of_items = len(array_to_sort)
    print "sorted array: ", array_to_sort

    for i in range(0, number_of_items-1):
        if array_to_sort[i] > array_to_sort[i+1]:
            tmp = array_to_sort[i]
            array_to_sort[i] = array_to_sort[i+1]
            array_to_sort[i+1] = tmp
            sort = True
    if sort:
        return my_sort(array_to_sort)
    else:
        return array_to_sort

if __name__ == '__main__':
    # main()

    arr = [4,5,7,3,2,1]
    test = my_sort(arr)
    print (test)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM