【发布时间】:2014-09-12 00:15:06
【问题描述】:
>>> a = np.arange(9).reshape((3, 3))
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> def sub(a):
... return a[:2, :2]
...
>>> sub(a)
array([[0, 1],
[3, 4]])
>>> sub(a) = np.arange(4).reshape((2, 2))
File "<stdin>", line 1
SyntaxError: cant assign to function call
>>> t = a[:2, :2]
>>> t = np.arange(4).reshape((2, 2))
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> a[:2, :2] = np.arange(4).reshape((2, 2))
>>> a
array([[0, 1, 2],
[2, 3, 5],
[6, 7, 8]])
这很明显为什么会这样:当我输入t = .. 时,我只是将t '重新链接'到内存中的其他数据。但问题是:
- 我怎样才能破解它并将对子矩阵的引用传递到函数之外?和
- 仍然可以更改此子矩阵的值吗?
【问题讨论】:
-
分配给函数调用不是有效的 Python 语法。你可以先
x = sub(a)然后x = np.arange(4).reshape((2, 2)),但我假设你知道这一切? -
嘿,想知道我的解决方案是否对您有所帮助?
标签: python function numpy matrix reference