python3' NoneType'对象不支持项目分配

时间:2018-02-09 23:35:19

标签: python python-3.x

当我尝试从python列表中添加bottomList到linkList时出现错误 我的代码是:

def Eight():

aList = [7,12,14,5,9,6]
def createList(pythonList,linkList = None):
    for i in pythonList:
        linkList = addBottom(linkList,i)
    return linkList
def addBottom(aList,value):
    ptr = aList
    if ptr == None:
        return {'data':value,'next':None}
    while ptr != None:
        ptr = ptr['next']
    ptr['next'] = {'data':value,'next':None}
    return aList
print(createList(aList))

错误:

Traceback (most recent call last): 
File "<pyshell#3>", line 1, in <module> Eight() 
File "C:\Users\17yz77\Downloads\Problem.py", line 164, in Eight 
    print(createList(aList)) 
File "C:\Users\17yz77\Downloads\Problem.py", line 151, in 
    createList linkList = addBottom(linkList,i) 
File "C:\Users\17yz77\Downloads\Problem.py", line 161, in 
    addBottom ptr['next'] = {'data':value,'next':None} 
TypeError: 'NoneType' object does not support item assignment 

2 个答案:

答案 0 :(得分:1)

您正试图到达结构的末尾,然后扩展它。问题是你的循环让你跑到最后。 None是一个常数;你不能改变它的价值。相反,停在最后一个节点:

while ptr['next'] is not None:
    ptr = ptr['next']

# ptr is now the last node in the sequence.
ptr['next'] = {'data':value,'next':None}

另请注意,isis not最好是检查None。许多其他帖子都提供了这方面的原因。

答案 1 :(得分:0)

while ptr != None:
    ptr = ptr['next']
    # !!! At this point in the code, ptr is None !!!
ptr['next'] = {'data':value,'next':None}

由于None代表任何内容,因此您无法将项目分配给None