【问题标题】:Don't understand why this Python function returns a None while it's definitely not a None locally不明白为什么这个 Python 函数返回 None 而它在本地绝对不是 None
【发布时间】:2016-06-15 14:51:52
【问题描述】:

我有一个 Python 函数,它遍历一个被解析为树的句子,寻找形容词/名词对(例如“好猫”),创建一个此类对的列表,然后返回它。这里是:

def traverse(t):
     thelist = list()
     try:
         t.label()
     except AttributeError:
          return
     else:
         if t.label() == 'NP': 
             for leaf in t.leaves():
                  thelist.append(str(leaf[0]))
             print("The list is ",thelist)
             return thelist
         else:
             for child in t:
                  traverse(child)   

我这样称呼这个函数:

 print("traversing the tree returned ",traverse(pos_parser))

我得到的是这样的:

The list is  ['good', 'cat']
traversing the tree returned  None

所以它在遍历中创建并打印出变量“thelist”,但不返回它(而是返回 None)。为什么??

有人可以帮忙吗?

【问题讨论】:

  • 注意:属性错误中的return隐式返回None
  • 您是否尝试过在调试器中单步执行?是否遇到 AttributeError 异常?

标签: python recursion scope


【解决方案1】:

我猜您第一次通过traverse 函数时,您会遇到递归调用traverse 的最后一行。但是,您不会对该调用的输出执行任何操作。我的猜测是您应该需要修改最后一行以捕获遍历调用的输出,然后最终返回列表。

按原样,您只在叶节点调用上调用 return

类似这样的:

def traverse(t): thelist = list() try: t.label() except AttributeError: return else: if t.label() == 'NP': for leaf in t.leaves(): thelist.append(str(leaf[0])) print("The list is ",thelist) return thelist else: for child in t: thelist.append(traverse(child)) return thelist

【讨论】:

    猜你喜欢
    • 2019-11-23
    • 2020-10-17
    • 2013-02-17
    • 2015-07-03
    • 2021-03-21
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多