gpt4 book ai didi

python - ndarray 的浅拷贝功能

转载 作者:太空宇宙 更新时间:2023-11-04 00:39:26 24 4
gpt4 key购买 nike

如果我有一个列表 x = [1, 2, 3] 并将它传递给一个使用运算符 += 的函数 f > 以f(x[:])的形式进行浅拷贝,内容不变:

def f(x):
print "f, x = ", x, ", id(x) = ", id(x)
x += [1]
print "f, x = ", x, ", id(x) = ", id(x)

x = [1,2,3]
print "x = ", x, ", id(x) = ", id(x)
f(x[:])
print "x = ", x, ", id(x) = ", id(x)

输出:

x =  [1, 2, 3] , id(x) =  139701418688384
f, x = [1, 2, 3] , id(x) = 139701418790136
f, x = [1, 2, 3, 1] , id(x) = 139701418790136
x = [1, 2, 3] , id(x) = 139701418688384

但是,期望 ndarray x = np.array([1, 2, 3]) 的行为相同,令我惊讶的是内容发生了变化,甚至尽管确实制作了副本:

import numpy as np

def f(x):
print "f, x = ", x, ", id(x) = ", id(x)
x += [1]
print "f, x = ", x, ", id(x) = ", id(x)

x = np.array([1,2,3])
print "x = ", x, ", id(x) = ", id(x)
f(x[:])
print "x = ", x, ", id(x) = ", id(x)

输出:

x =  [1 2 3] , id(x) =  139701418284416
f, x = [1 2 3] , id(x) = 139701418325856
f, x = [2 3 4] , id(x) = 139701418325856
x = [2 3 4] , id(x) = 139701418284416

(我知道 +[1] 函数对于 ndarray 和列表​​的作用不同)。我怎样才能像列表一样传递一个 ndarray 并避免这种行为?

奖励问题 为什么在函数 f 中使用 x = x + [1] 可以解决问题?

最佳答案

您可以使用 copy numpy 数组的方法,如果你想要一个副本:

f(x.copy())

请注意,即使 xx[:]id 不同,这些数组也可能共享相同的内存 所以对一个的更改将传播到另一个,反之亦然:

x = np.array([1,2,3])
y = x[:]
np.may_share_memory(x, y) # True

z = x.copy()
np.may_share_memory(x, z) # False

但是通常您不会将副本传递给函数。您将在函数内创建一个副本:

def give_me_a_list(lst):
lst = list(lst) # makes a shallow copy
# ...


def give_me_an_array(arr):
arr = np.array(arr) # makes a copy at least if you don't pass in "copy=False".
# ...

关于python - ndarray 的浅拷贝功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42497227/

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