Python unsubscriptable

前端 未结 4 625
慢半拍i
慢半拍i 2021-01-03 19:12

What does unsubscriptable mean in the context of a TypeError as in:

TypeError: \'int\' object is unsubscriptable

EDIT: Short c

相关标签:
4条回答
  • 2021-01-03 19:31

    It means you tried treating an integer as an array. For example:

    a = 1337
    b = [1,3,3,7]
    print b[0] # prints 1
    print a[0] # raises your exception
    
    0 讨论(0)
  • 2021-01-03 19:48

    I solved this converting my variable from list to array!

    import numpy as np
    my_list = API.get_list()
    my_array = np.array(my_list)
    

    Even working and be a false positive, this solved my 'problem'

    0 讨论(0)
  • 2021-01-03 19:55

    You are trying to lookup an array subscript of an int:

    >>> 1[0]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object is unsubscriptable
    

    That is, square brackets [] are the subscript operator. If you try to apply the subscript operator to an object that does not support it (such as not implementing __getitem__()).

    0 讨论(0)
  • 2021-01-03 19:56

    The problem in your sample code is that the array "a" contains two different types: it has 4 2-element lists and one integer. You are then trying to sub-script every element in "a", including the integer element.

    In other words, your code is effectively doing:

    print [1,2][0]
    print [5,3][0]
    print 5[0]
    print [5,6][0]
    print [2,2][0]
    

    That middle line where it does "5[0]" is what is generating the error.

    0 讨论(0)
提交回复
热议问题