TypeError: unsupported operand type(s) for -: 'list' and 'list'

前端 未结 4 975
心在旅途
心在旅途 2020-12-06 04:47

I am trying to implement the Naive Gauss and getting the unsupported operand type error on execution. Output:

  execfile(filename, namespace)
  File \"/media         


        
相关标签:
4条回答
  • 2020-12-06 04:57

    This question has been answered but I feel I should also mention another potential cause. This is a direct result of coming across the same error message but for different reasons. If your list/s are empty the operation will not be performed. check your code for indents and typos

    0 讨论(0)
  • 2020-12-06 05:05

    The operations needed to be performed, require numpy arrays either created via

    np.array()

    or can be converted from list to an array via

    np.stack()

    As in the above mentioned case, 2 lists are inputted as operands it triggers the error.

    0 讨论(0)
  • 2020-12-06 05:16

    Use Set in Python

    >>> a = [2,4]
    >>> b = [1,4,3]
    >>> set(a) - set(b)
    set([2])
    
    0 讨论(0)
  • 2020-12-06 05:21

    You can't subtract a list from a list.

    >>> [3, 7] - [1, 2]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for -: 'list' and 'list'
    

    Simple way to do it is using numpy:

    >>> import numpy as np
    >>> np.array([3, 7]) - np.array([1, 2])
    array([2, 5])
    

    You can also use list comprehension, but it will require changing code in the function:

    >>> [a - b for a, b in zip([3, 7], [1, 2])]
    [2, 5]
    

    >>> import numpy as np
    >>>
    >>> def Naive_Gauss(Array,b):
    ...     n = len(Array)
    ...     for column in xrange(n-1):
    ...         for row in xrange(column+1, n):
    ...             xmult = Array[row][column] / Array[column][column]
    ...             Array[row][column] = xmult
    ...             #print Array[row][col]
    ...             for col in xrange(0, n):
    ...                 Array[row][col] = Array[row][col] - xmult*Array[column][col]
    ...             b[row] = b[row]-xmult*b[column]
    ...     print Array
    ...     print b
    ...     return Array, b  # <--- Without this, the function will return `None`.
    ...
    >>> print Naive_Gauss(np.array([[2,3],[4,5]]),
    ...                   np.array([[6],[7]]))
    [[ 2  3]
     [-2 -1]]
    [[ 6]
     [-5]]
    (array([[ 2,  3],
           [-2, -1]]), array([[ 6],
           [-5]]))
    
    0 讨论(0)
提交回复
热议问题