NumPy数组传递值 [英] Numpy array pass-by-value
问题描述
我有一个由函数更改的numpy数组. 调用函数后,我要继续使用数组的初始值(调用修改函数之前的值)
I have a numpy array that is changed by a function. After calling the function I want to proceed with the initial value of the array (value before calling the modifying function)
# Init of the array
array = np.array([1, 2, 3])
# Function that modifies array
func(array)
# Print the init value [1,2,3]
print(array)
是否可以通过值传递数组,或者我有义务进行深层复制?
Is there a way to pass the array by value or am I obligated to make a deep copy?
推荐答案
正如我提到的,np.ndarray
对象是可变数据结构.这意味着在对对象进行更改时,任何引用特定对象的变量都将反映更改.
As I mentioned, np.ndarray
objects are mutable data structures. This means that any variables that refer to a particular object will all reflect changes when a change is made to the object.
但是,请记住,最个用于转换数组的numpy函数会返回新的数组对象,而原始数组则保持不变.
However, keep in mind that most numpy functions that transform arrays return new array objects, leaving the original unchanged.
在这种情况下,您需要执行的操作取决于您正在执行的操作.如果您的函数在适当的地方修改了相同的数组,那么您需要将副本传递给该函数.您可以使用 np.ndarray.copy
.
What you need to do in this scenario depends on exactly what you're doing. If your function modifies the same array in place, then you'll need to pass a copy to the function. You can do this with np.ndarray.copy
.
这篇关于NumPy数组传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!