3

我不明白在第一个示例中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]
4

2 回答 2

5
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
于 2018-05-02T12:52:19.397 回答
1

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

在第二个示例中 - 您在声明 a = [1,2,3] 时显式更改了“参考”

如果要解决此问题,请从冒泡排序函数返回一个不同的实例(不要更改正在发送的实际列表,创建一个新列表并返回它 - 这是您在 C 中使用指针所做的事情,在 python 中较少)。

无论哪种方式,都在 python 中阅读了一些可变/不可变类型 - https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747(谷歌上的第一个结果)。

于 2018-05-02T12:43:59.537 回答