话不多说,直接看代码。
def assign(a):
a[0] = 5 #in-place 修改
def assign_2(a):
a = [2, 3, 4] #直接赋值
print("a:{} address of a:{}".format(a, id(a)))
x = [1, 2, 3]
print("x:{} address of x:{}".format(x, id(x)))
assign(x)
print("x:{} address of x:{}".format(x, id(x)))
assign_2(x)
print("x:{} address of x:{}".format(x, id(x)))
最后输出:
x:[1, 2, 3] address of x:2478430233344
x:[5, 2, 3] address of x:2478430233344
a:[2, 3, 4] address of a:2478431575744
x:[5, 2, 3] address of x:2478430233344
说明,assign成功改变了x,是按地址修改。
而assign_2自动新建了一个变量(从地址可以看出来),并未修改x。
Pytorch的Tensor与列表同理。
本文通过示例代码展示了Python中变量赋值的两种方式,即按地址修改与创建新对象。在`assign`函数中,直接修改列表`x`的第一个元素,表明是按地址修改。而在`assign_2`函数中,重新赋值导致创建了新对象,原始列表`x`并未改变。这同样适用于PyTorch的Tensor操作。
670

被折叠的 条评论
为什么被折叠?



