a=[1,1,1,1,1,1,1,1,1]
b=[0,0,0,0,0,0,0,0,0]
c=[1,1,1,1,1,0,0,0,0]
def xor(a,b):
for i in range(len(a)):
a[i]=a[i]^b[i]
return a;
The first operation is like this, which is not consistent with expectations:
b=xor(a,c)
b,a=a,b
a=[0, 0, 0, 0, 0, 1, 1, 1, 1] | b=[0, 0, 0, 0, 0, 1, 1, 1, 1]
The second method is to add an intermediate value to temporarily store list b. The result is as follows:
mid=b
b=xor(a,c)
a=mid
a=[0, 0, 0, 0, 0, 0, 0, 0, 0] | b=[0, 0, 0, 0, 0, 1, 1, 1, 1]
淡淡烟草味2017-05-24 11:37:35
Actually, I don’t quite understand what you mean by “difference in results”. Isn’t your output very normal? xor(a,c)
, 将列表a的每个元素, 和列表c的每个元素取异或结果, 导致列表变成结果a变成[0, 0, 0, 0, 0, 1, 1, 1, 1]
While modifying list a, the xor function also returns a list a and assigns it to b. In this way, aren’t b and a the same list?
The "intermediate variable" below just stores the previous value of b. If you want to use the first method to achieve the effect of the second method, then you can replace it directly instead of assigning it to b
xor(a,c)
b,a=a,b
print a, b
大家讲道理2017-05-24 11:37:35
The first method is to change the value of b, and then exchange a and b. The second method is to define a new value mid, then change the value of b, and then assign mid to a
伊谢尔伦2017-05-24 11:37:35
def xor(a,b):
for i in range(len(a)):
a[i]=a[i]^b[i]
return a;
The essence of this function is to return a, there may be modifications in the middle, and then
print id(a)
print id(b)
b=xor(a,c) # <-- 就是 b==a
print id(a) == id(b) # <-- 调换之后应该相等了
b,a=a,b # <-- 这里两个都是指向同一个东西了
If there are just two swaps:
a, b = b, a # <-- 这样就好了