新手請教關於swap兩個值
各位好,我寫了三個swap值的程式碼。
發現第一個跟第三個成功,第二個的失敗。
第二個與第三個差別是一個在function裡執行,一個沒有。
但第一個也是在function裡執行,卻成功了@_@
我的想法是這或許跟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
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.200.196.251
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1545176246.A.BDC.html
推
12/19 07:49,
6年前
, 1F
12/19 07:49, 1F
→
12/19 10:32,
6年前
, 2F
12/19 10:32, 2F
→
12/19 10:32,
6年前
, 3F
12/19 10:32, 3F
→
12/19 12:55,
6年前
, 4F
12/19 12:55, 4F
→
12/19 14:27,
6年前
, 5F
12/19 14:27, 5F
推
12/19 15:58,
6年前
, 6F
12/19 15:58, 6F
推
12/19 16:55,
6年前
, 7F
12/19 16:55, 7F
推
12/19 17:01,
6年前
, 8F
12/19 17:01, 8F
推
12/20 02:47,
6年前
, 9F
12/20 02:47, 9F
→
12/20 02:47,
6年前
, 10F
12/20 02:47, 10F
推
12/20 02:50,
6年前
, 11F
12/20 02:50, 11F
Python 近期熱門文章
PTT數位生活區 即時熱門文章