Python 交换两个变量的值
今天梳理一下Python中交换变量值的方法
借助临时变量
a = 2 b = 4 c = a a = b b = c print(a) # 4 print(b) # 2
不借助临时变量
a = 2 b = 4 a = a + b # 2 + 4 = 6 b = a - b # 6 - 4 = 2 a = a - b # 6 - 2 = 4 print(a) print(b)
第三种方式 很简洁
a = 2 b = 4 a, b = b, a print(a) print(b)