sort()返回None [英] 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首先但是
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都不为您扔掉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
另外 返回[] 永远不会返回,上述其他情况不允许它返回.
in addition return[] will never return, the above else does not allow it to.
这篇关于sort()返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!