各位好,我寫了三個swap值的程式碼。
發現第一個跟第三個成功,第二個的失敗。
第二個與第三個差別是一個在function裡執行,一個沒有。
但第一個也是在function裡執行,卻成功了@[email protected]
我的想法是這或許跟python的pass by reference的特性有關?
求高手解釋,謝謝!
#swap experiment1, swap via function through list index, success
def swap(items, i, j):
tmp = items[i]
items[i] = items[j]
items[j] = tmp
s = [0, 1]
print(s) #before swap -> [0,1]
swap(s, 0, 1)
print(s) #after swap ->[1,0]
#swap experiment2, swap via function, fail
def swap1(a, b):
tem = a
a = b
b = tem
a = 0
b = 1
print(a) #before swap -> 0
swap1(a,b)
print(a) #after swap -> 0 why?
#swap experiment3, swap without function, success
x = 0
y = 1
print(x) #before swap -> 0
tem = x
x = y
y = tem
print(x) #after swap -> 1