Python中的插入符运算符(^)有什么作用?

Fry*_*Fry 103 python operators caret

今天我在python中遇到了插入操作符并尝试了它,我得到了以下输出:

>>> 8^3
11
>>> 8^4
12
>>> 8^1
9
>>> 8^0
8
>>> 7^1
6
>>> 7^2
5
>>> 7^7
0
>>> 7^8
15
>>> 9^1
8
>>> 16^1
17
>>> 15^1
14
>>>
Run Code Online (Sandbox Code Playgroud)

它似乎基于8,所以我猜是某种字节操作?我似乎找不到很多关于这个搜索网站的信息,除了它对于浮点数表现得很奇怪,是否有任何人有这个运算符的链接或者你能解释一下吗?

Chr*_*heD 154

这是一个按位异或(异或).

如果一个(并且只有一个)操作数(计算结果为)为true,则结果为true.

展示:

>>> 0^0
0
>>> 1^1
0
>>> 1^0
1
>>> 0^1
1
Run Code Online (Sandbox Code Playgroud)

要解释一个你自己的例子:

>>> 8^3
11
Run Code Online (Sandbox Code Playgroud)

以这种方式思考:

1000  # 8 (binary)
0011  # 3 (binary)
----  # APPLY XOR ('vertically')
1011  # result = 11 (binary)

  • 稍微更具说明性的示例可能包括在同一位中具有"1"的两个数字,以清楚地表明"1 xor 1 = 0". (13认同)
  • 我想补充一点,您可以通过键入“0bX”来计算二进制数,其中 X 是您的二进制数。`0b0001`、`0b0010` 等等。所以,`0b1101 ^ 0b1110` 会给你 `0b0011`(或 3)。 (2认同)

Ign*_*ams 39

它根据需要调用对象的__xor__()or或__rxor__()方法,对于整数类型,它按位进行异或运算.

  • +1表示在整数运算之外它真正*做了什么. (4认同)

Ale*_*lli 12

这是一个一点一点的独家或.二进制按位运算符记录在Python语言参考的第5章中.


ely*_*ely 8

一般来说,符号^是或方法的中版本.无论在符号的右侧和左侧放置什么数据类型,都必须以兼容的方式实现此功能.对于整数,它是常用操作,但是例如,对于具有类型的类型,没有函数的内置定义:__xor____rxor__XORfloatint

In [12]: 3 ^ 4
Out[12]: 7

In [13]: 3.3 ^ 4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-858cc886783d> in <module>()
----> 1 3.3 ^ 4

TypeError: unsupported operand type(s) for ^: 'float' and 'int'
Run Code Online (Sandbox Code Playgroud)

关于Python的一个巧妙之处是你可以在自己的类中覆盖这种行为.例如,在某些语言中,^符号表示取幂.你可以这样做,就像一个例子:

class Foo(float):
    def __xor__(self, other):
        return self ** other
Run Code Online (Sandbox Code Playgroud)

那么这样的东西就会起作用,而现在,对于这种情况Foo,^符号将意味着取幂.

In [16]: x = Foo(3)

In [17]: x
Out[17]: 3.0

In [18]: x ^ 4
Out[18]: 81.0
Run Code Online (Sandbox Code Playgroud)

  • 作为旁注,这些的“__r*__”版本(如“__rxor__”或“__radd__”)将从出现在中缀符号*右侧*的参数中调用,并且仅当调用左手符号的功能不起作用。你可以把它想象成 `try: left_hand_symbol.__xor__(right_hand_symbol); except: right_hand_symbol.__rxor__(left_hand_symbol)`,但 `xor` 可以替换为 [Python 数据模型](http://docs.python.org/3.1/reference/datamodel.html?突出显示=rlshift)。 (2认同)

tim*_*geb 5

当您使用^操作符时,在幕后__xor__调用该方法。

a^b相当于a.__xor__(b)

此外,a ^= b等效于a = a.__ixor__(b)__xor____ixor__通过 using 隐式调用^=但不存在时, where用作后备)。

原则上,做什么__xor__完全取决于它的实现。Python 中的常见用例是:

  • 集合的对称差(所有元素恰好出现在两个集合之一中)

演示:

>>> a = {1, 2, 3}
>>> b = {1, 4, 5}
>>> a^b
{2, 3, 4, 5}
>>> a.symmetric_difference(b)
{2, 3, 4, 5}
Run Code Online (Sandbox Code Playgroud)
  • 两个整数的位的按位不相等

演示:

>>> a = 5
>>> b = 6
>>> a^b
3
Run Code Online (Sandbox Code Playgroud)

解释:

    101 (5 decimal)
XOR 110 (6 decimal)
-------------------
    011 (3 decimal)
Run Code Online (Sandbox Code Playgroud)