“TypeError: 'function' 对象不支持项目分配"

2023-10-19Python开发问题
4

本文介绍了“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' object does not support item assignment

为什么?我该如何解决这个问题?

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 等于矩阵,这将支持索引和项分配.

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' 对象不支持项目分配"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10