Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

python - How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

def Ancestors (otu,tree):
    if tree[otu][0][0] == None:
       return []
    else:
        return [otu,tree[otu][0][0]] + Ancestors (tree[otu][0][0],tree)

The problem essentially is that at some point, the function tries to call a something which is None, this happens instead of the function returning the list that I want. I thought the if statement had accounted for that, but it would seem I was wrong. Any advice?

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

This is what tree is

{'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)]}

with otu referring to any of the strings in the tree.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This simply means that either tree, tree[otu], or tree[otu][0] evaluates to None, and as such is not subscriptable. Most likely tree[otu] or tree[otu][0]. Track it down with some simple debugging like this:

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

or pdb


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...