>> Python中的运算符

时间:2010-08-05 04:29:21

标签: python operators

>>运营商做了什么?例如,以下操作10 >> 1 = 5做了什么?

5 个答案:

答案 0 :(得分:41)

这是正确的位移操作符,将所有位“向右移动”。

二进制10是

1010

向右移动,转向

0101

是5

答案 1 :(得分:19)

>><<右移左移位操作符,即它们会改变二进制表示形式number(它也可以用在其他数据结构上,但Python没有实现)。它们是按__rshift__(self, shift)__lshift__(self, shift)定义的。

示例:

>>> bin(10) # 10 in binary
1010
>>> 10 >> 1 # Shifting all the bits to the right and discarding the rightmost one
5 
>>> bin(_) # 5 in binary - you can see the transformation clearly now
0101 

>>> 10 >> 2 # Shifting all the bits right by two and discarding the two-rightmost ones
2
>>> bin(_)
0010

快捷方式:只需执行一个整数除法(即丢弃剩余部分,在Python中将其实现为//),数字乘以2,增加到位数你正在转移。

>>> def rshift(no, shift = 1):
...     return no // 2**shift
...     # This func will now be equivalent to >> operator.
...

答案 2 :(得分:6)

您实际上可以自己重载右移操作(&gt;&gt;)。

>>> class wierd(str): 
... def __rshift__(self,other): 
... print self, 'followed by', other 
... 
>>> foo = wierd('foo') 
>>> bar = wierd('bar') 
>>> foo>>bar 
foo followed by bar 

参考:http://www.gossamer-threads.com/lists/python/python/122384

答案 3 :(得分:3)

它是right shift运营商。

二进制文件中的

10 1010现在>> 1表示右移1,有效地丢失最低有效位以提供101,即5 {1}}以二进制表示。

实际上divides数字为2

答案 4 :(得分:2)

请参阅Python参考手册中的5.7 Shifting Operations部分。

  

他们将第一个参数转移到了   按位数向左或向右   由第二个论点给出。