在函数中重塑numpy数组不会

2024-10-01 09:27:00 发布

您现在位置:Python中文网/ 问答频道 /正文

。。。但是更改numpy数组的值是可行的:

import numpy as np

def reshapeArray(arr):
    arr = arr.reshape((2, 2))
    arr /= 10
    print(arr) # prints [[0.1 0.3], [0.2 0.4]]

arr = np.array([1, 2, 3, 4], dtype=np.float32)
reshapeArray(arr)
print(arr) # prints [0.1 0.2 0.3 0.4]

reshapeArray()函数永久更改数组的值,但临时更改数组的形状。如果我在函数的末尾添加一个返回行(return arr),并将函数的输出赋给数组(arr = reshapeArray(arr)),那么这次就可以了。但是我想知道为什么它不返回数组就不能工作?你知道吗


Tags: 函数importnumpydefasnp数组prints
2条回答

尝试从函数返回数组,并将返回值赋给所需变量:

    return arr  # The last string of your function

arr = reshapeArray(arr)

从文档(numpy.reshape):

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

arr = arr / 10相反,它确实创建一个拷贝并重新分配它。你知道吗

显然,离开范围时会丢失一个视图。。。你知道吗

相关问题 更多 >