在 python 中分配被视为对象的副本

assigned in python considered as a copy of an object

我不明白为什么在第一个例子中,b 被认为是 a 的副本,它会随着 a 而改变,但在第二个例子中不会

def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp
    return  alist

a=[3,2,1]
b=a
a=bubbleSort(a)
print(a)
print(b)

输出:

[1, 2, 3]
[1, 2, 3]

a=[3,2,1]
b=a
a=[1,2,3]

print(a)
print(b)

输出:

[1, 2, 3]
[3, 2, 1]

在您的第一个示例中 - 您将 'reference' 发送到 a 和 b 之间共享的列表(并更改它)。

在第二个示例中 - 您在声明 a = [1,2,3]

时明确更改了 'reference'

如果您想解决此问题,return 一个与冒泡排序函数不同的实例(不要更改正在发送的实际列表,创建一个新列表并 return 它 - 这是一个问题你用 C 中的指针来做,而不是 python).

在 python - https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747(google 上的第一个结果)中阅读了一些关于可变/不可变类型的信息。

a=[3,2,1]
b=a # **here you're refrencing by memory not value**
a=bubbleSort(a)

print id(a) 
print id(b)

# these both will give you same memory reference

print(a)
print(b)

在第二个示例中,当您执行 b=a 时,您通过内存进行引用,但是当您执行 a=[1,2,3] 时,您将 a 关联到新的内存引用 b 仍然绑定到旧版本。

a = [3,2,1]
b=a

print id(b) #4376879184
print id(a) #4376879184


#they will be having the same id

a = [1,2,3]
#now you have assigned a new address which will have the new array

print id(b) #4376879184
print id(a) #4377341464
#they will be having different id now