为什么返回时空列表会变成NoneType?

时间:2016-09-17 01:15:10

标签: python list python-2.7 return nonetype

我正在研究一些路径查找算法,下面的代码段应该在从目标到开始的路径中创建一个节点数组。当有从目标到开始的路径时,它工作正常。但是当从开始到目标没有路径时,while循环永远不会运行,结果将返回[](这是正确的)。

def path(goal, pathToParentLookup):
    currentNode = goal
    result = []
    while(currentNode in pathToParentLookup):
        currentNode = pathToParentLookup[currentNode]
        result.append(currentNode)

    return result

#bidirectional search from start to goal finds the mid point of "center"
start_path = path(center, pathBack_start).reverse()
goal_path = path(center, pathBack_goal)
return start_path + [center] + goal_path

但是我收到此错误:

<ipython-input-14-ca3cb26b31ce> in bidirectional_search(graph, start, goal, searchMethod)
     46             start_path = path(center, pathBack_start).reverse()
     47             goal_path = path(center, pathBack_goal)
---> 48             return start_path + [center] + goal_path
     49
     50

TypeError: can only concatenate list (not "NoneType") to list

3 个答案:

答案 0 :(得分:3)

那不是正在发生的事情。问题是在line 46上为start_path分配了path()返回的列表上调用reverse()的结果。 没关系,但由于[].reverse()总是返回None,我确定它不是您想要的。

我认为你想要的是:

#bidirectional search from start to goal finds the mid point of "center"
start_path = path(center, pathBack_start)
start_path.reverse() 
goal_path = path(center, pathBack_goal)
return start_path + [center] + goal_path

答案 1 :(得分:1)

因为reverse是具有None返回类型的就地操作。

x = [1, 2]
print(x)
[1, 2]
a = x.reverse()
print(a)
None
print(x)
[2, 1]

不要将start_path分配给反向结果。将其分配给start_path = path(center,pathBack_start),然后调用start_path.reverse()

答案 2 :(得分:0)

[].reverse()返回None,您不应该指定返回值,因为它会就地修改列表。

见下文:

Python 2.7.11 (default, Dec  5 2015, 14:44:53) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.1.76)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print [].reverse()
None
>>>