[英]Strange error involving “AttributeError: 'NoneType' object has no attribute 'append' ”
so i am trying to parse out a text file by converting it to a list and splitting each item in the list at the space. 所以我试图通过将文本文件转换为列表并在空格处拆分列表中的每个项目来解析出一个文本文件。
i have created a test variable to run this part of the code by itself. 我创建了一个测试变量来单独运行这部分代码。 my code in the spyder editor:
我在spyder编辑器中的代码:
test = ['NC_009142.1_03_012_002_001 560', 'NC_017586.1_13_009_003_001 555', 'NC_016111.1_13_010_003_001 555']
ListOfLinesParsed = test
PN_List = []
counter_iterative = 0
while counter_iterative < len(ListOfLinesParsed):
PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0])
counter_iterative += 1
print PN_List
Which returns an error: 返回错误:
runfile(r'/home/jake/.spyder2/.temp.py', wdir=r'/home/jake/.spyder2')
运行文件(r'/ home / jake / .spyder2 / .temp.py',wdir = r'/ home / jake / .spyder2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-
packages/spyderlib/widgets/externalshell/sitecustomize.py", line 493, in runfile
execfile(filename, namespace)
File "/home/jake/.spyder2/.temp.py", line 7, in <module>
PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0])
AttributeError: 'NoneType' object has no attribute 'append'
BUT if i enter the commands directly into the terminal i get no error: 但是,如果我直接将命令输入到终端,则不会出错:
testL = []
testL = []
testL.append(test[0].split()[0])
testL.append(test [0] .split()[0])
testL
测试
['NC_009142.1_03_012_002_001']
testL.append(test[1].split()[0])
testL.append(test [1] .split()[0])
testL
测试
['NC_009142.1_03_012_002_001', 'NC_017586.1_13_009_003_001']
testL.append(test[2].split()[0])
testL.append(test [2] .split()[0])
testL
测试
['NC_009142.1_03_012_002_001', 'NC_017586.1_13_009_003_001', 'NC_016111.1_13_010_003_001']
Shouldn't the 2 things be EXACTLY the same? 这两件事不应该完全一样吗? i don't understand why the one in my script is acting any differently than the terminal commands.
我不明白为什么我的脚本中的命令与终端命令的行为有所不同。
The line 线
PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0])
is the problem. 是问题。
list.append
is an in-place operation, which returns None
, but alters the original list itself. list.append
是就地操作,它返回None
,但会更改原始列表本身。 If you assign PN_List
to the result, it becomes None
. 如果将
PN_List
分配给结果,则它将变为None
。 If you don't, then your program will run smoothly. 如果您不这样做,那么您的程序将顺利运行。 This is why when you try appending things without an assignment, you get the expected answer.
这就是为什么当您尝试在没有分配任务的情况下追加内容时,会得到预期答案的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.