What does it mean to have an index to scalar variable error? python

前端 未结 3 532
长情又很酷
长情又很酷 2021-01-03 18:03
import numpy as np

with open(\'matrix.txt\', \'r\') as f:
    x = []
    for line in f:
        x.append(map(int, line.split()))
f.close()

a = array(x)

l, v = eig         


        
相关标签:
3条回答
  • 2021-01-03 18:28

    In my case, I was getting this error because I had an input named x and I was creating (without realizing it) a local variable called x. I thought I was trying to access an element of the input x (which was an array), while I was actually trying to access an element of the local variable x (which was a scalar).

    0 讨论(0)
  • 2021-01-03 18:45

    IndexError: invalid index to scalar variable happens when you try to index a numpy scalar such as numpy.int64 or numpy.float64. It is very similar to TypeError: 'int' object has no attribute '__getitem__' when you try to index an int.

    >>> a = np.int64(5)
    >>> type(a)
    <type 'numpy.int64'>
    >>> a[3]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: invalid index to scalar variable.
    >>> a = 5
    >>> type(a)
    <type 'int'>
    >>> a[3]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object has no attribute '__getitem__'
    
    0 讨论(0)
  • 2021-01-03 18:46

    exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

    Did you mean to say:

    L = identity(len(l))
    for i in xrange(len(l)):
        L[i][i] = exponent[i]
    

    or even

    L = diag(exponent)
    

    ?

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