排序()返回无

sort() returns None(排序()返回无)
本文介绍了排序()返回无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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 即使它在两种情况下应该返回一个空列表:

The code outputs None even though it should return an empty list in two cases:

return []

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

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

Details: The code is for a list sorting module I am making for python practice (I am relatively new at python). sort1 is a modified mergesort.

推荐答案

@reut 先解决了,但是

@reut got to it first but

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 为[1] 且b2 为none,则您将a2 丢弃.我猜这是无意的.

Your setting both to [] if either is none meaning if a2 is [1] and b2 is none your throwing away a2. I'm guessing this is unintended.

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

Also in your code you have an uppercase S in the lower sortClass

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

in addition return[] will never return, the above else does not allow it to.

这篇关于排序()返回无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)