如何在递归函数中纠正"TypeError:'NoneType'对象不可订阅"?

The*_*oxx 14 python

def Ancestors (otu,tree):
    if tree[otu][0][0] == None:
       return []
    else:
        return [otu,tree[otu][0][0]] + Ancestors (tree[otu][0][0],tree)
Run Code Online (Sandbox Code Playgroud)

问题本质上是在某些时候,函数试图调用一个None的东西,而不是返回我想要的列表的函数.我认为if语句已经解释了,但看起来我错了.有什么建议?

Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    Ancestors('A',a)
  File "C:\x.py", line 129, in Ancestors
    return [otu,tree[otu][0][0]] + Ancestors (tree[otu][0][0],tree)
  File "C:\x.py", line 129, in Ancestors
    return [otu,tree[otu][0][0]] + Ancestors (tree[otu][0][0],tree)
  File "C:\x.py", line 129, in Ancestors
    return [otu,tree[otu][0][0]] + Ancestors (tree[otu][0][0],tree)
  File "C:\x.py", line 129, in Ancestors
    return [otu,tree[otu][0][0]] + Ancestors (tree[otu][0][0],tree)
  File "C:\x.py", line 126, in Ancestors
    if tree[otu][0][0] == None:
TypeError: 'NoneType' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)

这就是树

{'A': [('AD', 4.0), None, None], 'C': [('ADBFGC', 14.5), None, None], 'B': [('BF', 0.5), None, None], 'E': [('ADBFGCE', 17.0), None, None], 'D': [('AD', 4.0), None, None], 'G': [('BFG', 6.25), None, None], 'F': [('BF', 0.5), None, None], 'ADBFG': [('ADBFGC', 6.25), ('AD', 4.25), ('BFG', 2.0)], 'BF': [('BFG', 5.75), ('B', 0.5), ('F', 0.5)], 'ADBFGC': [('ADBFGCE', 2.5), ('ADBFG', 6.25), ('C', 14.5)], 'ADBFGCE': [None, ('ADBFGC', 2.5), ('E', 17.0)], 'BFG': [('ADBFG', 2.0), ('BF', 5.75), ('G', 6.25)], 'AD': [('ADBFG', 4.25), ('A', 4.0), ('D', 4.0)]}
Run Code Online (Sandbox Code Playgroud)

otu指的是树中的任何字符串.

phi*_*est 22

这只是意味着要么tree,tree[otu]tree[otu][0]计算结果为None,因此不是标化.最有可能tree[otu]tree[otu][0].通过一些简单的调试来跟踪它:

def Ancestors (otu,tree):
    try:
        tree[otu][0][0]
    except TypeError:
        print otu, tre[otu]
        raise
    #etc...
Run Code Online (Sandbox Code Playgroud)

或者pdb