python - TypeError: __getitem__() takes exactly 2 arguments (2 given) TypeError? ( python 3)

标签 python python-3.x typeerror

我定义了以下函数:

def eigval(matrix):
    a = matrix[0, 0]
    b = matrix[0, 1]
    c = matrix[1, 0]
    d = matrix[1, 1]
    c1 = (a + d) + sqrt((4 * b * c) + ((a - d)**2))
    c2 = (a + d) - sqrt((4 * b * c) + ((a - d)**2))
    return c1 / 2, c2 / 2

创建它是为了找到 2 X 2 矩阵的特征值。我用它在矩阵上迭代运行 Jacobi 算法。传入的矩阵是一个字典,以元组为键表示位置,以 float 为值。这个函数将在大约 6 次迭代中正常工作,但随后我会得到:

TypeError: __getitem__() takes exactly 2 arguments (2 given) 

在 block 的第一行(带有 a 的行)。

我对此完全感到困惑,因为正如我所说,它可以正常运行大约 6 次然后停止。

编辑:这是一个创建我要传入的矩阵类型的函数: (鉴于每次迭代的矩阵都会不同)

def create():
    matrix = {}
    matrix[0, 0] = 2
    matrix[0, 1] = 1
    matrix[1, 0] = 1
    matrix[1, 1] = 2
    return matrix

非常感谢任何帮助! (P.S. 第一篇文章在这里)

最佳答案

你的矩阵是一个使用元组作为键的字典,这可能不是你想要做的。

尝试使用嵌套列表:

from math import sqrt

def create():
    matrix = [[1, 2], [1, 2]]
    return matrix

def eigval(matrix):
    a = matrix[0][0]
    b = matrix[1][0]
    c = matrix[0][1]
    d = matrix[1][1]
    c1 = (a + d) + sqrt((4 * b * c) + ((a - d)**2))
    c2 = (a + d) - sqrt((4 * b * c) + ((a - d)**2))
    return [c1 / 2, c2 / 2]

>>> m = create() 
>>> eigval(m)
[3.0, 0.0]

或者使用 numpy:

import numpy

def eigval(matrix):
    a = matrix[0, 0]
    b = matrix[1, 0]
    c = matrix[0, 1]
    d = matrix[1, 1]
    c1 = (a + d) + sqrt((4 * b * c) + ((a - d)**2))
    c2 = (a + d) - sqrt((4 * b * c) + ((a - d)**2))
    return numpy.array([c1 / 2, c2 / 2])

>>> m = numpy.array([[1, 2], [1, 2]])
>>> m
array([[1, 2],
       [1, 2]])
>>> eigvalues, eigvectors = numpy.linalg.eig(m)
>>> eigvalues
array([ 0.,  3.])

>>> eigval(m)
array([ 3.,  0.])

关于python - TypeError: __getitem__() takes exactly 2 arguments (2 given) TypeError? ( python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16008092/

相关文章:

python - 根据 django 中的条件提交带有帖子的表单

python - RefactoringTool : ParseError: bad input: type=22, 值 ='='

python - 为什么 str.endswith 不允许 "suffix"参数是一个列表?

python - 为导入的库静音 Pytest 库输出

python - 使用函数接受不是标识符的 kwargs 关键字参数是否安全?

javascript - 无法读取未定义的属性 'src'

python - 如何连接侵 eclipse 和膨胀无法连接的虚线?

python - 如何在 python 中创建悬挂指针(在堆栈或堆中)

python - 从 cx_Oracle 调用 oracle 过程

python - Django: AttributeError: 'NoneType' 对象没有属性 'split'