Home > front end >  TypeError: 'float' object is not subscriptable when accessing the float elements of a list
TypeError: 'float' object is not subscriptable when accessing the float elements of a list

Time:10-12

This code

import numpy as np
from math import sqrt
import itertools

class MyClass():
    id = itertools.count(start=1)

    def __init__(self, location = None):
        self.id = next(MyClass.id)
        self.location = np.random.uniform(0, 1, size=(1, 2)).tolist()[0]


    def __iter__(self):
        for _ in self.__dict__.values():
            yield _

    def f(self, obj):
        return sqrt((self.location[0][0] - obj.location[0][0]) ** 2   (self.location[0][1] - obj.location[0][1]) ** 2)

    def g(self, objs):
        flag = True
        for obj in objs:
            if self.f(obj) > 0.8:
                flag = False
                break
        return flag

def do():
    objs = []
    first_obj = MyClass()
    objs.append(first_obj)
    counter = 1
    while counter != 10:
        next_obj = MyClass()
        if next_obj.g(objs):
            objs.append(next_obj)
            counter = counter   1
    return objs

objs = do()

returns

return sqrt((self.location[0][0] - obj.location[0][0]) ** 2   (self.location[0][1] - obj.location[0][1]) ** 2)
TypeError: 'float' object is not subscriptable

But I don't understand why because location here is a list of two elements (One may note the tolist() function applied to location in the constructor of MyClass class.). So, why isn't OK to access its elements by [.][.] syntax?

CodePudding user response:

Your accessing location is a list and it's a single array list rather not a 2D List from where you can't subscribable and can't access like location[0][0] or location[0][1]. Do you instead use like location[0] and location[1]

def f(self, obj):
    print(self.location)
    print(obj.location)
    return sqrt((self.location[0] - obj.location[0]) ** 2   (self.location[1] - obj.location[1]) ** 2)

Output

[0.7281687101439013, 0.972072020630831]
[0.8743260151470964, 0.3612891339626867]

----------------------------------------

[0.8608823868671358, 0.8073941973113157]
[0.3413812202951577, 0.5149064923284026]
  • Related