【发布时间】:2016-12-07 12:16:31
【问题描述】:
我正在尝试在 python 中实现快速排序。这是我的代码:
def quicksort(numbers):
less = []
is_pivot = []
larger = []
if len(numbers) > 1:
pivot = numbers[0]
for x in numbers:
if x < pivot:
less.append(x)
elif x == pivot:
is_pivot.append(x)
else:
larger.append(x)
sorted_list = quicksort(less) + is_pivot + quicksort(larger)
print(sorted_list)
else:
print(numbers)
这给了我以下错误信息:
File "sortingalgorithms.py", line 101, in <module>
quicksort(numbers)
File "sortingalgorithms.py", line 66, in quicksort
sorted_list = quicksort(less) + is_pivot + quicksort(larger)
File "sortingalgorithms.py", line 66, in quicksort
sorted_list = quicksort(less) + is_pivot + quicksort(larger)
TypeError: unsupported operand type(s) for +: 'NoneType' and 'list'
当我尝试在不连接它们的情况下打印列表时,我会得到以下输出,其中包含数字 3、2、1 的列表
[1.0]
[]
[None, [2.0], None]
[]
[None, [3.0], None]
非类型元素来自哪里,我该如何解决我的问题?谢谢
【问题讨论】:
-
你没有
return语句,所以你的函数返回None
标签: python list concatenation quicksort nonetype