加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:04:17 所属栏目:Python 来源:网络整理
导读:我不明白在第一个例子中,b被认为是a的副本的原因,它会随着第二个例子而变化 def bubbleSort(alist): for passnum in range(len(alist)-1,-1): for i in range(passnum): if alist[i]alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp re
我不明白在第一个例子中,b被认为是a的副本的原因,它会随着第二个例子而变化

def bubbleSort(alist):
    for passnum in range(len(alist)-1,-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,3]
[1,3]

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

print(a)
print(b)

输出:

[1,3]
[3,1]

解决方法

a=[3,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,3]你将a关联到一个新的内存引用b仍然绑定到旧的内存.

a = [3,1]
b=a

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


#they will be having the same id

a = [1,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读