当我尝试从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
答案 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}
另请注意,is
和is 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
。