编程语言
首页 > 编程语言> > 在python中分配,被视为对象的副本

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

作者:互联网

我不明白在第一个例子中,b被认为是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]

解决方法:

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你正在通过内存引用,但当你做了= [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

标签:bubble-sort,python,object
来源: https://codeday.me/bug/20190731/1587401.html