python3“NoneType”对象不支持项赋值

2024-05-20 15:02:26 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图将bottom从python列表添加到链接列表时出错 我的代码是:

def八():

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))

错误:

^{pr2}$

Tags: none列表datareturnvalue链接defnext
2条回答

然后,你要延伸到结构的末端。问题是你的循环让你走到尽头。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和{}更好的方法是检查{}。原因可以在许多其他帖子中找到。在

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

无法将项分配给None,因为None不代表任何内容。在

相关问题 更多 >