类型错误:不支持“-”的操作数类型为“列表”和“列表”。

40

我正在尝试实现朴素高斯消元算法,在执行时遇到了“不支持的操作数类型”错误。

  execfile(filename, namespace)
  File "/media/zax/MYLINUXLIVE/A0N-.py", line 26, in <module>
    print Naive_Gauss([[2,3],[4,5]],[[6],[7]])
  File "/media/zax/MYLINUXLIVE/A0N-.py", line 20, in Naive_Gauss
    b[row] = b[row]-xmult*b[column]
TypeError: unsupported operand type(s) for -: 'list' and 'list'
>>>   

这是代码

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

print Naive_Gauss([[2,3],[4,5]],[[6],[7]])

1
这是你的问题代码行:b[row] = b[row]-xmult*b[column]。row是一个列表,而b[column]也是一个列表,所以你试图从一个列表中减去另一个列表,这(正如错误输出告诉你的那样)是不支持的操作。 - Jon Kiparsky
谢谢@JonKiparsky,那真的很有帮助。 - Iliass
4个回答

55

你不能从列表中减去另一个列表。

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

使用numpy是实现这个的简单方法:

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

您也可以使用列表推导式,但这将需要更改函数中的代码:

>>> [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]]))

28

Python中使用Set

>>> a = [2,4]
>>> b = [1,4,3]
>>> set(a) - set(b)
set([2])

2
需要执行的操作需要使用通过np.array()创建的numpy数组,或者可以通过np.stack()将列表转换成数组。
在上述情况中,如果输入的操作数为2个列表,则会触发错误。

0

这个问题已经得到了解答,但我认为我还应该提及另一个可能的原因。这是因为遇到了相同的错误信息,但原因不同。如果您的列表为空,则不会执行操作。检查您的代码缩进和拼写错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接