Python不能连接列表,因为它们包含非类型元素

时间:2016-12-07 12:16:31

标签: python list concatenation quicksort nonetype

我试图在python中实现quicksort。这是我的代码:

/usr/lib/jvm/java-1.8.0-ibm-1.8.0.3.20-1jpp.1.el7_2.x86_64/jre/bin/java -Xms100m -Xmx500m \
$'-Dcom.sun.management.jmxremote\r' \
-Dflume.monitoring.type=http \
-Dflume.monitoring.port=34545 \
-cp '/staging001/Flume/server/conf:/staging001/Flume/server/lib/*:/lib/*' \
-Djava.library.path= org.apache.flume.node.Application \
-f /staging001/Flume/server/conf/flume.conf -n client

这给了我以下错误消息:

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)

当我尝试打印列表而不连接它们时,我得到以下输出以获得数字为3,2,1的列表

  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'

非类型元素来自何处,以及如何解决我的问题?感谢

2 个答案:

答案 0 :(得分:1)

好的,问题只来自这条线:

sorted_list = quicksort(less) + is_pivot + quicksort(larger)

在这里仔细考虑,你的功能不会返回任何东西。因此,quicksort(less)quicksort(larger)将返回None

因此,sorted_list变为[None, [2.0], None]

基本上,用print语句替换return行,然后在函数外打印。

这是我的解决方案:

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)
        return sorted_list # Replaced print statement here.
    else:
        return numbers  # Replaced print statement here.

print(quicksort([1,3,4,2,5,0]))

答案 1 :(得分:0)

当你需要返回这样的内容时,你的函数会返回None

def quickSort(numbers):
    less = []
    is_pivot = []
    larger = []

    if len(numbers) <= 1:
        return numbers
    else:
        pivot = numbers[0]
        for x in numbers:
            if x < pivot:
                less.append(x)
            elif x > pivot:
                larger.append(x)
            else:
                is_pivot.append(x)
        less = quickSort(less)
        larger = quickSort(larger)
        return less + is_pivot + larger

test = [87, 3, 42, -893, -5, 107, 3, 27, 0]
test = quickSort(test)
print(test)

输出:

[-893, -5, 0, 3, 3, 27, 42, 87, 107]

试试here!