Python appending error

北城余情 提交于 2019-12-13 09:34:39

问题


x = []
with open(filechoice) as fileobj:
    for word in fileobj:  
       for ch in word:

           f = ord(ch)
           x = x.append(ord(ch))

But it returns this error:

"AttributeError: 'NoneType' object has no attribute 'append'"

How can I fix this error?


回答1:


The list.append() method returns None, and you replaced the list stored in x with that return value:

x = x.append(ord(ch))

Don't assign back to x here; list.append() alters the list in place:

with open(filechoice) as fileobj:
    for word in fileobj:  
       for ch in word:
           x.append(ord(ch))

You can use a list comprehension to build the list instead:

with open(filechoice) as fileobj:
    x = [ord(ch) for word in fileobj for ch in word]


来源:https://stackoverflow.com/questions/29954520/python-appending-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!