附加列表,但是错误‘ NoneType’对象没有属性‘ append’

我有一个脚本,其中我提取每个用户的值,并添加到一个列表中,但我得到“‘ 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

我想在名单中添加姓氏。如果没有,那么不要添加到名单中。请帮助 注意: p 是我用来从我的模块中获取信息的对象,这个模块中包含了所有的名字、姓氏、年龄等等... ... 请提示... ... 预先感谢

322365 次浏览

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

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

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

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.

list is mutable

Change

last_list=last_list.append(p.last_name)

to

last_list.append(p.last_name)

will work

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.