python - 类型错误:不支持的操作数类型 - : 'list' 和 'list'

标签 python python-2.7 list typeerror operands

我正在尝试实现朴素高斯并在执行时出现不受支持的操作数类型错误。 输出:

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

最佳答案

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

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

关于python - 类型错误:不支持的操作数类型 - : 'list' 和 'list',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26685679/

相关文章:

Python 2.7 查找一个字符串的某些变位词是否是另一个字符串的子字符串

Python:加载 CSV,第一列作为行名,第一行作为列名

Python 从键列表和值列表列表构建一个字典

python - 在 Python 的 while 循环中追加列表时出现错误消息 'List index out of range'

python - 与Python子进程通信

python - 使用 'try' 批量重命名 Pandas DF 列

python - 如何在 python 中使用 hex()?

对象列表中的 Python 返回具有类属性集的第一个对象

python - 当 QComboBox 设置为可编辑时

python - pandas:删除数据帧 A 中未出现在数据帧 B 中的索引