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)
一般来说,符号^是或方法的中缀版本.无论在符号的右侧和左侧放置什么数据类型,都必须以兼容的方式实现此功能.对于整数,它是常用操作,但是例如,对于具有类型的类型,没有函数的内置定义:__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)
当您使用^操作符时,在幕后__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)