Python附加错误 [英] Python appending error

查看:118
本文介绍了Python附加错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但它返回此错误:

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

如何解决此错误?

推荐答案

list.append()方法返回 None ,并且您已替换存储在 x 中且具有返回值的列表:

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

x = x.append(ord(ch))

不要分配回 x 在这里; list.append()修改列表

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]

这篇关于Python附加错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆