gpt4 book ai didi

python - 在函数中 reshape numpy 数组不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 23:56:28 25 4
gpt4 key购买 nike

...但是改变 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)),这它起作用的时间。但我想知道为什么它不返回数组就不起作用?

最佳答案

来自文档(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 不同,它会创建一个副本并重新分配它。

显然,离开作用域时 View 丢失了...

关于python - 在函数中 reshape numpy 数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57570915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com