Python 附加列表但错误“NoneType”对象没有属性“附加”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12894795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
appending list but error 'NoneType' object has no attribute 'append'
提问by learner
I have a script in which I am extracting value for every user and adding that in a list but I am getting "'NoneType' object has no attribute 'append'". My code is like
我有一个脚本,我在其中为每个用户提取值并将其添加到列表中,但我得到“'NoneType' 对象没有属性 'append'”。我的代码就像
last_list=[]
if p.last_name==None or p.last_name=="":
pass
last_list=last_list.append(p.last_name)
print last_list
I want to add last name in list. If its none then dont add it in list . Please help Note:p is the object that I am using to get info from my module which have all first_name ,last_name , age etc.... Please suggest ....Thanks in advance
我想在列表中添加姓氏。如果没有,则不要将其添加到 list 中。请帮助注意:p 是我用来从我的模块中获取信息的对象,其中包含所有 first_name ,last_name ,age 等......请建议......提前谢谢
回答by Cédric Julien
When doing pan_list.append(p.last)you're doing an inplace operation, that is an operation that modifies the object and returns nothing (i.e. None).
当pan_list.append(p.last)你在做一个就地操作时,这是一个修改对象并且不返回任何内容的操作(即None)。
You should do something like this :
你应该做这样的事情:
last_list=[]
if p.last_name==None or p.last_name=="":
pass
last_list.append(p.last) # Here I modify the last_list, no affectation
print last_list
回答by Joe Day
I think what you want is this:
我想你想要的是这个:
last_list=[]
if p.last_name != None and p.last_name != "":
last_list.append(p.last_name)
print last_list
Your current if statement:
您当前的 if 语句:
if p.last_name == None or p.last_name == "":
pass
Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.
实际上从不做任何事情。如果 p.last_name 为 none 或空字符串,则它在循环内不执行任何操作。如果 p.last_name 是别的东西,则跳过 if 语句的主体。
Also, it looks like your statement pan_list.append(p.last)is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.
此外,看起来您的语句pan_list.append(p.last)是一个错字,因为我没有看到 pan_list 和 p.last 在您发布的代码中的任何其他地方使用。
回答by jessiejcjsjz
list is mutable
列表是可变的
Change
改变
last_list=last_list.append(p.last_name)
to
到
last_list.append(p.last_name)
will work
将工作
回答by Jayesh Mishra
You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-
您不应该将它分配给任何变量,当您在列表中附加某些内容时,它会自动更新。仅使用:-
last_list.append(p.last)
if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.
如果您再次将其分配给变量“last_list”,它将不再是列表(将成为无类型变量,因为您尚未为其声明类型)并且 append 在下一次运行中将变得无效。

