TypeError: 'float' object is not subscriptable–

Advertisements

I want to calculate the average value of every three lines of data in the text. The error is as follows:

Traceback (most recent call last):
  File "/home/code/test1.py", line 7, in <module>
    lines = sum(lines[i:i+3])/3
TypeError: 'float' object is not subscriptable

with open('/home/data/NB_accuracy_score.txt', 'r') as f:
    lines = f.readlines()
    lines = [line.strip().split('\t') for line in lines]
    lines = [line[1] for line in lines]
    lines = [float(line) for line in lines]    
    for i in range(0, len(lines), 3):
        lines = sum(lines[i:i+3])/3
        with open('/home/data/NB_accuracy_score.txt', 'a') as f:
            f.write('{}\t{}\n'.format('average', lines))

The text content and format are shown below:

Column2 0.8706781511585587
Column3 0.8781303616921717
Column4 0.9750610907956535
Column5 0.8173341883156271
Column6 0.8251156825704927
Column7 0.9717335921387844
Column8 0.8588412679156341
Column9 0.8584079998613542
Column10    0.9994454168905218
Column11    0.779847836259337
Column12    0.8211296164711184
Column13    0.8471776918944213
Column14    0.7776295038214243
Column15    0.7964853295436821
Column16    0.8513024037711652
Column17    0.7580284570458051
Column18    0.8333651063239805
Column19    0.8280272438952531
Column20    0.705100431534982
Column21    0.8970728410252855
Column22    0.7650993916916518

How can I improve my code so that the results are correct?

>Solution :

You overwrite the lines variable in your for loop: lines = sum(lines[i:i+3])/3. During the second iteration, lines is a float, so trying to run lines[i:i+3] will throw an error (i.e., you cannot do 1.23[0:3].

To fix this, use a variable name other than lines. Below, I renamed the variable to average.

for i in range(0, len(lines), 3):
    average = sum(lines[i:i+3])/3
    with open('/home/data/NB_accuracy_score.txt', 'a') as f:
        f.write('{}\t{}\n'.format('average', average))

Leave a ReplyCancel reply