【问题标题】:sort() returns None排序()返回无
【发布时间】:2016-04-15 02:07:46
【问题描述】:

代码:

import math
import time
import random
class SortClass(object):
    def sort1(self, l):
        if len(l)==1:
            return l
        elif len(l)==2:
            if l[0]<l[1]:
                return l
            else:
                return l[::-1]
        else:
            pivot=math.floor(len(l)/2)
            a=l[pivot:]
            b=l[:pivot]
            a2=self.sort1(a)
            b2=self.sort1(b)
            if a2==None or b2==None:
                a2=[]
                b2=[]
            return (a2+b2).sort()
        return []
Sort=SortClass()
x=[20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]
print(Sort.sort1(x))

代码输出 None 即使它在两种情况下应该返回一个空列表:

return []

a2=self.mergeSort(a)
b2=self.mergeSort(b)
if a2==None or b2==None:
    a2=[]
    b2=[]
return (a2+b2).sort()

详情: 该代码用于我为 python 练习制作的列表排序模块(我在 python 方面相对较新)。 sort1 是经过修改的归并排序。

【问题讨论】:

标签: python sorting python-3.x recursion return


【解决方案1】:

list.sort 返回None(就地排序):

>>> [].sort() is None
True

你在这里使用它:

return (a2+b2).sort()

使用sorted 排序到新列表而不是就地:

return sorted(a2+b2)

【讨论】:

    【解决方案2】:

    @reut 先到了,但是

    return sorted(a2+b2)
    

    不是

    return (a2+b2).sort()
    

    另外

    if a2 == None or b2 == None:
        a2 = []
        b2 = []
    

    应该是

    if a2 == None:
        a2 = []
    if b2 == None:
        b2 = []
    

    如果a2 为[1] 且b2 为none,则您将两者都设置为[] 如果其中任何一个都没有,则意味着您要丢弃a2。我猜这是无意的。

    在您的代码中,您在较低的 sortClass 中有一个大写的 S

    此外 返回[] 永远不会回来,上面的else不允许它。

    【讨论】:

    • 修正了我帖子的语法/拼写。
    • 检查 Nones 只是因为它返回 None 但还是谢谢。
    猜你喜欢
    • 2020-02-04
    • 2021-09-07
    • 2018-04-29
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2017-06-29
    • 1970-01-01
    相关资源
    最近更新 更多