>> Python 中的运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3411749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
>> operator in Python
提问by AlexBrand
What does the >>operator do? For example, what does the following operation 10 >> 1 = 5do?
什么是>>运营商吗?例如,下面的操作是10 >> 1 = 5做什么的?
采纳答案by Eton B.
It's the right bit shift operator, 'moves' all bits once to the right.
这是正确的位移运算符,将所有位向右“移动”一次。
10 in binary is
二进制的 10 是
1010
1010
shifted to the right it turns to
向右移动它变成
0101
0101
which is 5
这是 5
回答by Zack The Human
See section 5.7 Shifting Operationsin the Python Reference Manual.
They shift the first argument to the left or right by the number of bits given by the second argument.
他们将第一个参数向左或向右移动第二个参数给出的位数。
回答by codaddict
Its the right shiftoperator.
它的right shift运营商。
10in binary is 1010now >> 1says to right shift by 1, effectively loosing the least significant bit to give 101, which is 5represented in binary.
10in binary1010现在>> 1说右移1,有效地丢失最低有效位给101,它5以二进制表示。
In effect it dividesthe number by 2.
实际上它divides的数字由2。
回答by Yatharth Agarwal
>>and <<are the Right-Shiftand Left-Shiftbit-operators, i.e., they alter the binary representation of the number (it can be used on other data structures as well, but Python doesn't implement that). They are defined for a class by __rshift__(self, shift)and __lshift__(self, shift).
>>和<<是右移和左移位运算符,即,它们改变数字的二进制表示(它也可以用于其他数据结构,但 Python 没有实现)。它们由__rshift__(self, shift)和为类定义__lshift__(self, shift)。
Example:
例子:
>>> 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
Shortcut:Just to perform an integer division (i.e., discard the remainder, in Python you'd implement it as //) on a number by 2 raised to the number of bits you were shifting.
快捷方式:只需对一个数字执行整数除法(即,丢弃余数,在 Python 中您将其实现为//) 2 升至您要移位的位数。
>>> def rshift(no, shift = 1):
... return no // 2**shift
... # This func will now be equivalent to >> operator.
...
回答by Alan Dong
You can actually overloads right-shift operation(>>) yourself.
您实际上可以自己重载右移操作(>>)。
>>> class wierd(str):
... def __rshift__(self,other):
... print self, 'followed by', other
...
>>> foo = wierd('foo')
>>> bar = wierd('bar')
>>> foo>>bar
foo followed by bar
Reference: http://www.gossamer-threads.com/lists/python/python/122384
参考:http: //www.gossamer-threads.com/lists/python/python/122384

