各位好,我写了三个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
作者: anotherday 2018-12-19 07:49:00
Case2, local & global variable