Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot append to list in for loop (even though it works for another code right above)

So I have a code to basically loop through a few different arrays and then split according to training and testing indexes before storing the results in a train and test. However, when executing it, it returns an error for the test even though the exact same code is used for train

the code is as follow:

train = []
test = []
for i in ho:
    temp = newarr[i]
    #print(temp)
    #make overall list
    li = list(range(0,24))
    #get training indexes
    trgidx = list(random.sample(range(0,23),12))

    #get testing indexes
    tstidx = list(set(li).symmetric_difference(set(trgidx)))
    
    #extract training samples for the class
    for trg in trgidx:
        trgsample = temp[:,trg]
        train.append(trgsample)
    #extract testing samples 
    for test in tstidx:
        print(test)
        testsample = temp[:,test]
        test.append(testsample)
        
train = np.array(train).T
test = np.array(test).T

The error is shown at line 21;
ho is simply a list from [0,1,2,3] with each instance stored in the corresponding array, newarr

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 19         print(test)
 20         testsample = temp[:,test]
 21         test.append(testsample)
 AttributeError: 'int' object has no attribute 'append'

Error is shown at line 21

The same code runs fine for the ‘train’ method, does anyone know where it’s going wrong?

>Solution :

for test in tstidx:

It has the same name test as the list test. Need to change one of the names.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading