2014-11-01 127 views
8

我想实现Naive Gauss并在执行时获得不支持的操作数类型错误。 输出:TypeError:不支持的操作数类型为 - :'list'和'list'

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]]) 
+0

这是你的问题线:'b [row] = b [row] -xmult * b [column]'row是一个列表,而b [column]是一个列表,所以你试着从另一个列表中减去一个列表,(错误输出告诉你)不是受支持的操作。 – 2014-11-01 02:24:21

+0

谢谢@JonKiparsky,这真的有帮助 – Ledruid 2014-11-06 06:31:15

回答

14

不能从列表中减去列表。

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

谢谢@falsetru,我用numpy数组,它的工作原理 – Ledruid 2014-11-06 06:35:12

+0

@Ledruid,欢迎来到Stack Overflow!如果这对你有帮助,你可以通过[接受答案]告诉社区(http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235)。 – falsetru 2014-11-06 07:05:41

2

使用设置在Pyth on

>>> a = [2,4] 
>>> b = [1,4,3] 
>>> set(a) - set(b) 
set([2]) 
相关问题