在本教程中,我们将讨论在 Python 程序中交换两个变量(n1 和 n2)而不使用第三个变量的不同方法。
示例:
P: 112
Q: 211
After swapping P and Q:
P: 211
Q: 112
方法 1:通过使用内置方法
内置方法可以处理任何数据类型值,如字符串、浮点、it。这种方法很容易使用。
Left, Right = Right, Left
示例:
P = JavaTpoint
Q = Tutorial
print ("Variables Value Before Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
# Method to swap 'P' and 'Q'
P, Q = Q, P
print ("Variables Value After Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
输出:
Variables Value Before Swapping:
Value of P: JavaTpoint
Value of Q: Tutorial
Variables Value After Swapping:
Value of P: Tutorial
Value of Q: JavaTpoint
方法 2:通过使用按位异或运算符
按位异或方法仅适用于整数,并且它的工作速度更快,因为它使用的位操作是针对相同的值结果= 0 和不同的值结果= 1。
P ^= Q
Q ^= P
P ^= Q
示例:
P = 5 # P = 0101
Q = 10 # Q = 1010
print ("Variables Value Before Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
# Method to swap 'P' and 'Q'
P ^= Q # P = 1111, Q = 1010
Q ^= P # Q = 0101, P = 1111
P ^= Q # P = 1010, Q = 0101
print ("Variables Value After Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
输出:
Variables Value Before Swapping:
Value of P: 5
Value of Q: 10
Variables Value After Swapping:
Value of P: 10
Value of Q: 5
方法 3:通过使用加法和减法运算符
此方法只能用于数值。
P = P + Q
Q = P - Q
P = P - Q
示例:
P = 112
Q = 211
print ("Variables Value Before Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
# Method to swap 'P' and 'Q'
P = P + Q # P = 323, Q = 211
Q = P - Q # P = 323, Q = 112
P = P - Q # P = 211, Q = 112
print ("Variables Value After Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
输出:
Variables Value Before Swapping:
Value of P: 112
Value of Q: 211
Variables Value After Swapping:
Value of P: 112
Value of Q: 211
方法 4:通过使用乘法和除法运算符
此方法只能用于除 0 以外的数值。
P = P * Q
Q = P / Q
P = P / Q
示例:
P = 11.2
Q = 21.1
print ("Variables Value Before Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
# Method to swap 'P' and 'Q'
P = P * Q # P = 236.32, Q = 21.1
Q = P / Q # P = 236.32, Q = 11.2
P = P / Q # P = 21.1, Q = 11.2
print ("Variables Value After Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
输出:
Variables Value Before Swapping:
Value of P: 11.2
Value of Q: 21.1
Variables Value After Swapping:
Value of P: 21.1
Value of Q: 11.2
方法 5:通过使用按位运算符和算术运算符
在这个方法中,我们将同时使用按位运算符和算术运算符。此方法仅适用于整数,不适用于浮点类型。
示例:
P = 112
Q = 211
print ("Variables Value Before Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
# Same as P = P + Q
P = (P & Q) + (P | Q) ;
# Same as Q = P - Q
Q = P + (~Q) + 1 ;
# Same as P = P - Q
P = P + (~Q) + 1 ;
print ("Variables Value After Swapping: ")
print ("Value of P: ", P)
print ("Value of Q: ", Q)
输出:
Variables Value Before Swapping:
Value of P: 112
Value of Q: 211
Variables Value After Swapping:
Value of P: 211
Value of Q: 112
结论
在本教程中,我们讨论了在不使用第三个变量的情况下交换两个变量的值的不同方法。