排序()返回无

2023-09-02Python开发问题
0

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

问题描述

代码:

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.

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

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11