我正在尝试“就地”修改一个 numpy 数组。我有兴趣在原地重新排列数组(而不是返回:重新排列数组的版本)。
这是一个示例代码:
from numpy import *
def modar(arr):
arr=arr[[1,0]] # comment & uncomment this line to get different behaviour
arr[:,:]=0
print "greetings inside modar:"
print arr
def test2():
arr=array([[4,5,6],[1,2,3]])
print "array before modding"
print arr
print
modar(arr)
print
print "array now"
print arr
test2()
赋值 ar=arr[[1,0]] 打破了“arr”与传递给函数“modar”的原始数组的对应关系。您可以通过注释/取消注释该行来确认这一点。当然,这是因为必须创建一个新数组。
我如何告诉 python 新数组仍然对应于“arr”?
简单地说,我怎样才能让“modar”重新排列阵列“就地”?
好的..我修改了该代码并将“modarr”替换为:
def modar(arr):
# arr=arr[[1,0]] # comment & uncomment this line to get different behaviour
# arr[:,:]=0
arr2=arr[[1,0]]
arr=arr2
print "greetings inside modar:"
print arr
例程“test2”仍然从“modar”获得一个未修改的数组。