Python TypeError:';的操作数类型不受支持;列表';和';列表';
我试图实现NaiveGauss,并在执行时得到不支持的操作数类型错误。 输出:Python TypeError:';的操作数类型不受支持;列表';和';列表';,python,python-2.7,list,typeerror,operands,Python,Python 2.7,List,Typeerror,Operands,我试图实现NaiveGauss,并在执行时得到不支持的操作数类型错误。 输出: 不能从列表中减去列表 >>> [3, 7] - [1, 2] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for -: 'list' and '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'
您也可以使用列表理解,但需要更改函数中的代码:
>>> [a - b for a, b in zip([3, 7], [1, 2])]
[2, 5]
>>将numpy作为np导入
>>>
>>>def Naive_Gauss(数组,b):
... n=len(数组)
... 对于xrange(n-1)中的列:
... 对于xrange中的行(列+1,n):
... xmult=Array[row][column]/Array[column][column]
... 数组[行][列]=xmult
... #打印数组[行][列]
... 对于X范围(0,n)中的列:
... 数组[行][col]=数组[行][col]-xmult*数组[列][col]
... b[行]=b[行]-xmult*b[列]
... 打印阵列
... 打印b
... 返回数组,b#>>print Naive_Gauss(np.Array([[2,3],[4,5]]),
…np.数组([[6],[7]]))
[[ 2 3]
[-2 -1]]
[[ 6]
[-5]]
(数组([[2,3],
[-2,-1]),数组([[6],
[-5]]))
在Python中使用Set
>>> a = [2,4]
>>> b = [1,4,3]
>>> set(a) - set(b)
set([2])
这个问题已经得到了回答,但我觉得我还应该提到另一个潜在的原因。这是由于遇到相同的错误消息但原因不同而直接导致的。如果列表为空,则不会执行该操作。检查代码是否存在缩进和键入需要执行的操作需要通过 np.array() 或者可以通过从列表转换为数组 np.stack()
与上述情况一样,输入两个列表作为操作数,这会触发错误 这是您的问题行:
b[row]=b[row]-xmult*b[column]
row是一个列表,而b[column]是一个列表,因此您试图从一个列表中减去另一个列表,这(正如错误输出告诉您的)是不受支持的操作。谢谢@JonKiparsky,这真的很有帮助
>>> 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]]))
>>> a = [2,4]
>>> b = [1,4,3]
>>> set(a) - set(b)
set([2])