如果两个列表的长度相同,您也可以通过使用索引和循环的旧交换方法来执行此操作。这是一种老派,但有助于理解索引
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
b = [0, 9, 8, 7, 6, 5, 4, 3, 2, 1]
for i in range(0, len(a)):
a[i] = a[i] + b[i]
b[i] = a[i] - b[i]
a[i] = a[i] - b[i]
print(a)
print(b)
这将使输出为:
[0,9,8,7,6,5,4,3,2,1]
[1,2,3,4,5,6,7,8,9,0]
或者也可以使用 Xor 来完成。Xor 运算符是按位运算符,例如在操作数之间进行 Xor 运算。
a = 5 #0b101
b = 4 #0b100
c = a ^ b #0b001
这0b101
是 50b100
的二进制表示,是 4 的二进制表示,当您对这些进行异或运算时,您将输出0b001
即 1 。如果一个且只有一个输入为 1,则异或返回 1 个输出结果。如果两个输入为 0 或两者均为 1,则输出 0 个结果。我们可以使用 Xor 交换两个变量,例如:
a = 5 # 0b0101
b = 9 # 0b1001
a = a ^ b # Xor (0b0101, 0b1001) = 0b1100 (12)
b = a ^ b # Xor (0b1100, 0b1001) = 0b0101 (5)
a = a ^ b # Xor (0b1100, 0b0101) = 0b1001 (9)
print("a = {} and b = {}".format(a, b))
输出将是a = 9 and b = 5
同样,我们也可以通过对其中的项目进行异或操作来交换两个列表,例如:
a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ]
b = [ 0, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
for i in range(0, len(a)) :
a[i] = a[i] ^ b[i]
b[i] = a[i] ^ b[i]
a[i] = a[i] ^ b[i]
print(a)
print(b)
输出:
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
让我们看另一个场景,如果我们需要交换列表中的项目,例如:我们有一个这样的列表x = [ 13, 3, 7, 5, 11, 1 ]
,我们需要像这样交换它的项目x = [ 1, 3, 5, 7 , 11, 13 ]
所以我们可以通过使用两个按位运算符 Xor^
和 Compliments来做到这一点~
代码 :
# List of items
a = [ 13, 3, 7, 5, 11, 1 ]
# Calculated the length of list using len() and
# then calulated the middle index of that list a
half = len(a) // 2
# Loop from 0 to middle index
for i in range(0, half) :
# This is to prevent index 1 and index 4 values to get swap
# because they are in their right place.
if (i+1) % 2 is not 0 :
#Here ~i means the compliment of i and ^ is Xor,
# if i = 0 then ~i will be -1
# As we know -ve values index the list from right to left
# so a [-1] = 1
a[i] = a[i] ^ a[~i]
a[~i] = a[i] ^ a[~i]
a[i] = a[i] ^ a[~i]
print(a)
所以输出将是[1, 3, 5, 7, 11, 13]