Python 中的 ^= 运算符是什么意思?
what does the ^= operator mean in Python?
^=
运算符在Python中是什么意思?
我上网查了一下,上面写着"Performs Bitwise xOR on operands and assign value to left operand"。
玩了一圈,还是一头雾水。谁能举例说明一下?
当只有奇数个条件为真时,XOR 将 returns 为真。
假设以下情况:
Condition A: False; Condition B: False => A XOR B = False
Condition A: False; Condition B: True => A XOR B = True
Condition A: True; Condition B: False => A XOR B = True
Condition A: True; Condition B: True => A XOR B = False
假设我们有以下代码:
a = True
b = True
b ^= a #b XOR a
print(b) #Result = False
c = True
d = False
d ^= c #d XOR c
print(d) #Result = True
回答 khelwood 对此答案的评论;
你必须先了解二进制(base-2)系统。因此,让我们以 6 号和 3 号为例。这些数字分别转换为 base-2 中的 0110 和 0011。当我们对数字执行 XOR 时,我们将对每个单独的位执行操作。
让位顺序为b3、b2、b1、b0。
在 b3 处,0 XOR 0 会给你 0
在 b2 处,1 XOR 0 会给你 1
在 b1 处,1 XOR 1 将得到 0
在b0处,0 XOR 1会得到1.
因此,结果是 base-2 中的 0101,即 base-10 中的 5
a = 6
b = 3
b ^= a
print(b) #Result = 5
^=
运算符在Python中是什么意思?
我上网查了一下,上面写着"Performs Bitwise xOR on operands and assign value to left operand"。
玩了一圈,还是一头雾水。谁能举例说明一下?
当只有奇数个条件为真时,XOR 将 returns 为真。
假设以下情况:
Condition A: False; Condition B: False => A XOR B = False
Condition A: False; Condition B: True => A XOR B = True
Condition A: True; Condition B: False => A XOR B = True
Condition A: True; Condition B: True => A XOR B = False
假设我们有以下代码:
a = True
b = True
b ^= a #b XOR a
print(b) #Result = False
c = True
d = False
d ^= c #d XOR c
print(d) #Result = True
回答 khelwood 对此答案的评论;
你必须先了解二进制(base-2)系统。因此,让我们以 6 号和 3 号为例。这些数字分别转换为 base-2 中的 0110 和 0011。当我们对数字执行 XOR 时,我们将对每个单独的位执行操作。
让位顺序为b3、b2、b1、b0。 在 b3 处,0 XOR 0 会给你 0 在 b2 处,1 XOR 0 会给你 1 在 b1 处,1 XOR 1 将得到 0 在b0处,0 XOR 1会得到1.
因此,结果是 base-2 中的 0101,即 base-10 中的 5
a = 6
b = 3
b ^= a
print(b) #Result = 5