简体   繁体   中英

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:

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

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.append(test[0].split()[0])

testL

['NC_009142.1_03_012_002_001']

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

['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. If you assign PN_List to the result, it becomes 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM