“TypeError:'function'对象不支持项目分配” [英] "TypeError: 'function' object does not support item assignment"

查看:155
本文介绍了“TypeError:'function'对象不支持项目分配”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个矩阵

fi = [[f1],           Nij = [[N11 N12 .......N1n],
      [f2],                  [N21 N22 .......N2n],
       .                            ...
       .                            ...
      [fn]]                  [Nn1 Nn2 .......Nnn]]

我想成倍增加:

f1 to each element of the 1st row,
f2 to each element of the 2nd row,

依此类推。

即我想 Xij = fi * Nij 其中fi是列矩阵,Xij& Nij是nxn矩阵。

I.e. I want Xij = fi*Nij where fi is a column matrix and Xij & Nij is nxn matrix.

我尝试使用

import numpy as np

fi = np.linspace(1,5, num =5)
fi = np.asmatrix(fi)

def Xij(ai):
    Nij = np.ones((5,5))
    for i in range(len(fi)):
    for j in range(len(fi)):
        Xij[i,j] = ai[i] * Nij[i,j]
return Xij

Zij = Xij(fi)

它给我这个错误 TypeError:'function'对象不支持项目分配

为什么?以及如何解决这个问题?

Why? and how do I solve this?

推荐答案

你的问题就在这里:

Xij[i,j] = ai[i] * Nij[i,j]

您将变量命名为 Xij ,但也是一个函数。此外,当您命名该函数时,它会覆盖变量。

You named a variable Xij, but also a function. Furthermore, when you named the function, it overwrote the variable.

因此,当您尝试索引函数并分配其项时,会生成错误,因为您不能在功能上做到这一点。以下是一个示例:

Because of this, when you try to index the function and assign its items, an error is generated because you can't do that on the function. Below is an example:

>>> def test(): print "Hi"
...
>>> test[1] = "yo!"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'function' object does not support item assignment
>>>

这个错误看起来很熟悉吗?它与您生成的相同,因为我完全按照您的方式执行了操作。

Does that error look familiar? It is the same one you generated because I did exactly what you did.

要解决此问题,请将您的函数名称更改为 Xij 。这样做会使 Xij 等于matrice,这将支持索引和项目分配。

To fix this problem, change the name of you function to something other than Xij. Doing so will make Xij equal the matrice, which will support indexing and item assignment.

这篇关于“TypeError:'function'对象不支持项目分配”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆