86

我有一个脚本,我在其中为每个用户提取值并将其添加到列表中,但我得到“'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 是我用来从我的模块中获取信息的对象,它具有所有 first_name ,last_name , age 等......请建议......提前致谢

4

4 回答 4

142

列表是可变的

改变

last_list=last_list.append(p.last_name)

last_list.append(p.last_name)

将工作

于 2017-04-29T07:18:28.613 回答
46

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
于 2012-10-15T11:52:02.630 回答
12

您不应该将其分配给任何变量,当您在列表中附加某些内容时,它会自动更新。仅使用:-

last_list.append(p.last)

如果您再次将其分配给变量“last_list”,它将不再是一个列表(将成为一个无类型变量,因为您尚未为其声明类型)并且 append 在下一次运行中将变得无效。

于 2020-01-01T13:45:13.177 回答
5

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.

于 2012-10-15T11:56:35.373 回答