【问题标题】:Why does an empty list become NoneType on return?为什么空列表在返回时变为 NoneType?
【发布时间】:2017-01-25 07:14:45
【问题描述】:

我正在研究一些寻路算法,下面的 sn-p 应该在从目标到起点的路径中创建一个节点数组。当有从目标到起点的路径时,它可以正常工作。但是当没有从起点到终点的路径时,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

【问题讨论】:

    标签: python list python-2.7 return nonetype


    【解决方案1】:

    [].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
    >>> 
    

    【讨论】:

      【解决方案2】:

      因为 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()

      【讨论】:

        【解决方案3】:

        这不是正在发生的事情。问题是在line 46 上,您将在path() 返回的列表上调用reverse() 的结果分配给start_path。 没关系,但由于 [].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
        

        【讨论】:

        • 或者,由于复制成本被基于语法的切片的廉价性所抵消(与方法调用的更高成本相比),您可以使用start_path = path(center, pathBack_start)[::-1]
        猜你喜欢
        • 1970-01-01
        • 2015-08-18
        • 1970-01-01
        • 2017-02-09
        • 2012-12-01
        • 2016-07-03
        • 1970-01-01
        • 2023-01-05
        • 2015-09-01
        相关资源
        最近更新 更多